Turning multidimensional array into one-dimensional array

PhpArraysMultidimensional Array

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

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];

Solution 2 - Php

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?.

Solution 3 - Php

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

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

Solution 4 - Php

This is really all there is to it:

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

Solution 5 - Php

foreach ($a as $v1) {
    foreach ($v1 as $v2) {
        echo "$v2\n";
    }
}

where $a is your array name. for details

Solution 6 - Php

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;
}

Solution 7 - Php

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

Solution 8 - Php

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; 
} 

Solution 9 - Php

This will make

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

Solution 10 - Php

$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"]

Solution 11 - Php

The quickest solution would be to use this array library:

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

which will produce exactly the array you want

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTomi SeusView Question on Stackoverflow
Solution 1 - PhpdecezeView Answer on Stackoverflow
Solution 2 - PhphakreView Answer on Stackoverflow
Solution 3 - PhpDon't PanicView Answer on Stackoverflow
Solution 4 - PhpGrexisView Answer on Stackoverflow
Solution 5 - Phpn00bView Answer on Stackoverflow
Solution 6 - PhpHamid NaghipourView Answer on Stackoverflow
Solution 7 - PhprrayView Answer on Stackoverflow
Solution 8 - PhpKunwar KishorView Answer on Stackoverflow
Solution 9 - PhpRutunj sheladiyaView Answer on Stackoverflow
Solution 10 - PhpRomanView Answer on Stackoverflow
Solution 11 - PhpMinworkView Answer on Stackoverflow