1

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Related snippet (for comparison): PHP function to get recursive path keys with path

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.