简体   繁体   中英

How to convert a two dimensional array into a one dimensional array

I have this kind of array

Array
(
    [0] => Array
    (
        [company_name] => Tata
    )

    [1] => Array
    (
        [company_name] => reliance
    )

    [2] => Array
    (
        [company_name] => nisan
    )

    [3] => Array
    (
        [company_name] => lg
    )
)

I need to flatten this to a one dimensional array. For example like this:

Array
(
    [0] => reliance
    [1] => cloud9
)

Is there any built-in functionality available for this array conversion?

You can flatten such an array by using the array_map() function. This function returns an array after running a callback over each item.

$array = [
    [ 'company_name' => 'Tata' ],
    [ 'company_name' => 'reliance' ],
    [ 'company_name' => 'nisan' ],
    [ 'company_name' => 'lg' ],
];

$newArray = array_map(function ($item) { return $item['company_name']; }, $array);

See this code on ideone .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM