How to "flatten" a multi-dimensional array to simple one in PHP?
This is a one line, SUPER easy to use:
$result = array();
array_walk_recursive($original_array,function($v) use (&$result){ $result[] = $v; });
It is very easy to understand, inside the anonymous function/closure. $v
is the value of your $original_array
.
If you specifically have an array of arrays that doesn't go further than one level deep (a use case I find common) you can get away with array_merge
and the splat operator.
<?php
$notFlat = [[1,2],[3,4]];
$flat = array_merge(...$notFlat);
var_dump($flat);
Output:
array(4) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
}
The splat operator effectively changes the array of arrays to a list of arrays as arguments for array_merge
.
$array = your array
$result = call_user_func_array('array_merge', $array);
echo "<pre>";
print_r($result);
REF: http://php.net/manual/en/function.call-user-func-array.php
Here is another solution (works with multi-dimensional array) :
function array_flatten($array) {
$return = array();
foreach ($array as $key => $value) {
if (is_array($value)){ $return = array_merge($return, array_flatten($value));}
else {$return[$key] = $value;}
}
return $return;
}
$array = Your array
$result = array_flatten($array);
echo "<pre>";
print_r($result);
Use array_walk_recursive
<?php
$aNonFlat = array(
1,
2,
array(
3,
4,
5,
array(
6,
7
),
8,
9,
),
10,
11
);
$objTmp = (object) array('aFlat' => array());
array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'), $objTmp);
var_dump($objTmp->aFlat);
/*
array(11) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
[6]=>
int(7)
[7]=>
int(8)
[8]=>
int(9)
[9]=>
int(10)
[10]=>
int(11)
}
*/
?>
Tested with PHP 5.5.9-1ubuntu4.24 (cli) (built: Mar 16 2018 12:32:06)