How to "flatten" a multi-dimensional array to simple one in PHP? [duplicate]
Solution 1:
$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);
Solution 2:
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
.