I'm trying to achieve something I naively believed would be simple: flattening a multidimensional array (which could have many nested levels) but still having arrays as a result. Ideally I'm looking for a function that can iterate through 10+ nested levels and can handle different set of keys (not necessarily always the same).
In short, turning this:
Array
(
[0] => Array
(
[0] => Array
(
[index] => -1
[qty] => 77
[id] => 7
)
[1] => Array
(
[index] => -1
[qty] => 83
[id] => 8
)
)
[1] => Array
(
[0] => Array
(
[index] => -1
[qty] => 75
[id] => 13
)
[1] => Array
(
[index] => -1
[qty] => 60
[id] => 14
[msr] => g
)
)
[2] => Array
(
[index] => -1
[qty] => 10
[id] => 12
)
)
Into this:
Array
(
[0] => Array
(
[index] => -1
[qty] => 77
[id] => 7
)
[1] => Array
(
[index] => -1
[qty] => 83
[id] => 8
)
[2] => Array
(
[index] => -1
[qty] => 75
[id] => 13
)
[3] => Array
(
[index] => -1
[qty] => 60
[id] => 14
[msr] => g
)
[4] => Array
(
[index] => -1
[qty] => 10
[id] => 12
)
)
This is what I had and thought would work, but I end up with a flat array with no key information (and if I want keys, every iteration overwrites the previous values and I end up with just the last array of them all):
function flatten_multi_array(array $array){
$ret_array = array();
foreach(new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value) {
$ret_array[] = $value;
}
return $ret_array;
}
4 Answers 4
function dig($source, &$out){
foreach ($source as $k => $v){
if (isset($v["index"]){
$out[] = $v;
} else {
dig($v, $out);
}
}
}
and that's it.
usage:
$out = array();
$source = array(); // your magic nested array
dig($source, $out);
and now $out
has what you need.
5 Comments
If you're still looking for the RecursiveIteratorIterator
approach, see the following:
foreach(new RecursiveIteratorIterator(new ParentIterator(new RecursiveArrayIterator($array)), RecursiveIteratorIterator::SELF_FIRST) as $value) {
if (isset($value['index']))
$ret_array[] = $value;
}
This should do it inside your function. See as well the demo.
Related: Quick Recursive search of all indexes within an array
1 Comment
Something like this untested code maybe...
$outArray = array();
foreach($originalArray as $nestedArray){
foreach($nestedArray as $innerArray){
$outArray[] = $innerArray;
}
}
print_r($outArray);
1 Comment
I see that this was just answered. Well, I thought I'd contribute my solution since I did it. :P
$newArray = array();
function isMulti($k,$v){
global $newArray;
if(is_array($v)){
foreach($v as $k2 => $v2){
if(!is_array($v2)){
$newArray[] = $v;
break;
}else{
isMulti($k2,$v2);
}
}
}
}
foreach($arrayInQuestion as $k => $v){
isMulti($k,$v);
}