I have an array that I've build dynamically. It has many nested arrays because of the way it's built, but the depth is useless to me, so I organize it right afterwards. It could look like this:
Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[0] => Array
(
[index] => -1
[cost] => 0.189956571618
)
)
)
)
[1] => Array
(
[index] => -1
[cost] => 2.18650011647
)
)
I want to almost-flatten this array (i.e. access its data using $array[$i]['cost'] on all entries, regardless if they were nested deep before I processed them). So far I've been using SPL recursion, with something along these lines:
function flatten($array) {
$return = array();
$it = new RecursiveIteratorIterator(new ParentIterator(new RecursiveArrayIterator($array)), RecursiveIteratorIterator::SELF_FIRST);
foreach($it as $value) {
if(isset($value['cost'])) {
$return[] = $value;
}
}
return $return;
}
It works for the most part, but some of the values in the original array, which do have a 'cost' index in them, fail to be added to the new array because they are passed as nested arrays themselves, like so:
Array
(
[0] => Array
(
[index] => -1
[cost] => 0.189956571618
)
[1] => Array
(
[index] => -1
[cost] => 2.18650011647
)
)
...instead of just (which most of the time I get):
Array
(
[index] => -1
[cost] => 0.189956571618
)
I thought the whole point of using a RecursiveIterator was to go deep within the array and fetch the entries which don't have arrays within them (i.e. the 'values' I want). Am I using the wrong tools for this job? If so, what would be more appropriate to loop through an array for which I don't know the depth? If SPL is the way to go, what am I doing wrong?
Thanks in advance.