Reputation: 1597
Given the following array structure:
$array = array('level1'=>array('level2'=>array('url'=>$url,'title'=>$title)));
using:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key=>$value) {
if(is_null($value)){
echo $key.' -- '.$value.'<br />';
}
}
I can echo out when a value is null, but what I don't know is the array path for that item
When this is a more complex array, I need to know that the path that had the null was $array['level1']['level2']['url']
for example.
currently I only know it was url
with no idea where in the structure the item actually was.
Using this iterator method, how can I work out what the path is so I can update the item in the array when its null?
Upvotes: 1
Views: 229
Reputation: 7896
You can achieve desirable path by using getDepth
and getSubIterator
function.
Have a look on below solution:
$url = null;
$title = null;
$array = array(
'level1' => array(
'level2' => array(
'level3' => array(
'url' => $url,
'title' => $title
)
),
)
);
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
$keys = array();
if (is_null($value)) {
$keys[] = $key;
for ($i = $iterator->getDepth() - 1; $i >= 0; $i--) {
$keys[] = $iterator->getSubIterator($i)->key();
}
$key_paths = array_reverse($keys);
echo "'{$key}' have null value which path is: " . implode(' --> ', $key_paths) . '<br>';
}
}
In above example $array
have 2 keys with null
value i.e. url and title. The variable $key_paths
contains desire path and the out put of above script will be:
'url' have null value which path is: level1 --> level2 --> level3 --> url
'title' have null value which path is: level1 --> level2 --> level3 --> title
Upvotes: 1