简体   繁体   中英

Getting reference item in RecursiveIteratorIterator

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?

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 ie 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM