Turning multidimensional array into one-dimensiona

2019-01-01 04:16发布

I've been banging my head on this one for a while now.

I have this multidimensional array:

Array
(
    [0] => Array
        (
            [0] => foo
            [1] => bar
            [2] => hello
        )

    [1] => Array
        (
            [0] => world
            [1] => love
        )

    [2] => Array
        (
            [0] => stack
            [1] => overflow
            [2] => yep
            [3] => man
        )

And I need to get this:

Array
(
    [0] => foo
    [1] => bar
    [2] => hello
    [3] => world
    [4] => love
    [5] => stack
    [6] => overflow
    [7] => yep
    [8] => man
)

Any ideas?

All other solutions I found solve multidimensional arrays with different keys. My arrays use simple numeric keys only.

10条回答
宁负流年不负卿
2楼-- · 2019-01-01 04:43

As of PHP 5.6 this can be done more simply with argument unpacking.

$flat = array_merge(...$array);
查看更多
浅入江南
3楼-- · 2019-01-01 04:45
foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

where $a is your array name. for details

查看更多
只若初见
4楼-- · 2019-01-01 04:48

This is really all there is to it:

foreach($array as $subArray){
    foreach($subArray as $val){
        $newArray[] = $val;
    }
}
查看更多
浅入江南
5楼-- · 2019-01-01 04:49
array_reduce($array, 'array_merge', array())

Example:

$a = array(array(1, 2, 3), array(4, 5, 6));
$result = array_reduce($a, 'array_merge', array());

Result:

array[1, 2, 3, 4, 5, 6];
查看更多
登录 后发表回答