60

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.

3

11 Answers 11

94
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];
Sign up to request clarification or add additional context in comments.

2 Comments

This is not necessarily the best way to do it, it may be somewhat cryptic for one; I just like the functional approach and writing one-liners for the exercise. ;o)
Second argument could be just 'array_merge'.
42

The PHP array_merge­Docs function can flatten your array:

$flat = call_user_func_array('array_merge', $array);

In case the original array has a higher depth than 2 levels, the SPL in PHP has a RecursiveArrayIterator you can use to flatten it:

$flat = iterator_to_array(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)), 0);

See as well: How to Flatten a Multidimensional Array?.

3 Comments

SPL RecursiveIteratorIterator class is the best possible solution when you have a mixed array (keys with both N dimension and keys as strings/ints/whatever not array).
It is return only array value not key. how can i get key & value both?
@ChiragPatel: Recursive iteration over (then multiple) array(s) often has key collisions. The recursive iteration however does provide keys as well, just set the second parameter $use_keys of iterator_to_array() to true, see php.net/iterator_to_array
26

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

$flat = array_merge(...$array);

2 Comments

As of PHP 7.4 this will also will work if $array has a count of zero (for exactly this use).
this is the most clear and simple solution today
13

This is really all there is to it:

foreach($array as $subArray){
    foreach($subArray as $val){
        $newArray[] = $val;
    }
}

1 Comment

its not linear or logN
3
foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

where $a is your array name. for details

2 Comments

This does not answer the question completly, he wants to populate a new array with the values. (However I do think they found a solution since the 2 years that this has been posted)
i also think that they found the result but i just wanted to share my view. thanks for the comment, no hard feelings :)
3

As of PHP 5.3 the shortest solution seems to be array_walk_recursive() with the new closures syntax:

function flatten(array $array) {
    $return = array();
    array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });
    return $return;
}

Comments

1

In PHP5.6 there other way to solve this problem, combining the functions, array_shift() to remove the first elemente of the original array, array_pus() to add items an new array, the important thing is the of ... splapt/elipse operator it will unpack the return of array_shitf() like an argument.

<?php

$arr = [
        ['foo', 'bar', 'hello'],
        ['world', 'love'],
        ['stack', 'overflow', 'yep', 'man', 'wow']
    ];

$new = [];
while($item = array_shift($arr)){
    array_push($new, ...$item);
}

print_r($new);

Output:

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

Example - ideone

1 Comment

Works only for single dimensional arrays. For mixed use, only working solution is $new = iterator_to_array(new \RecursiveIteratorIterator(new \RecursiveArrayIterator($myArray)), null);
1

I had used this code to resolve same type of problem. so you can also try this.

function array_flatten($array) { 

 if (!is_array($array))  
{ 
  return FALSE;  
}  
  $result = array(); 
foreach ($array as $key => $value)
{
  if (is_array($value))  
  {
   $result = array_merge($result, array_flatten($value));
  } 
  else  {
  $result[$key] = $value;   
  }  
}   
return $result; 
} 

Comments

1

This will make

array_walk_recursive($array, function($a) use (&$return) { $return[] = $a; });

Comments

0
$blocked_dates = array(
                    '2014' => Array
                        (
                            '8' => Array
                                (
                                    '3' => '1',
                                    '4' => '1',                                     
                                    '6' => '1',                                     
                                    '10' => '1',
                                    '15' => '1',
                                    '25' => '1'

                                )

                        ),
                    '2015' => Array
                        (
                            '9' => Array
                                (
                                    '3' => '1',
                                    '4' => '1',                                    
                                    '6' => '1',                                     
                                    '10' => '1',
                                    '15' => '1',
                                    '25' => '1'

                                )

                        )    

                );

RESUTL(ONE DIMENTIONAL ARRAY) :

$unavailable_dates = array();
foreach ($blocked_dates as $year=>$months) {

    foreach ($months as $month => $days) {

        foreach ($days as $day => $value) {

            array_push($unavailable_dates,"$year-$month-$day");
        }

    }
}



$unavailable_dates = json_encode($unavailable_dates);
print_r($unavailable_dates);

OUTPUT : ["2014-8-3","2014-8-4","2014-8-6","2014-8-10","2014-8-15","2014-8-25","2015-9-3","2015-9-4","2015-9-6","2015-9-10","2015-9-15","2015-9-25"]

Comments

-1

The quickest solution would be to use this array library:

$flattened = Arr::flatten($yourArray);

which will produce exactly the array you want

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.