Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP RecursiveArrayIterator class get key-value pair recursive

I tried to wrote a custom array iterator with PHP's factory class. My problem: I need all array's all datas, example, here is a simple PHP array:

Array
(
    [authentication] => Array
        (
            [basic] => Array
                (
                    [username] => guest
                    [password] => guest
                )

            [filters] => Array
                (
                    [price] => 100
                    [owener] => me
                )

        )

)

I see on PHP's doc page, I can use two simple class and iterate with simple foreach:

    $iterator = new \RecursiveIteratorIterator(new \RecursiveArrayIterator($this->phpArray));
    foreach($iterator as $key => $value) {
        $d = $iterator->getDepth();
        echo "depth: $d $key => $value\n";
    }

This program throw following output:

depth: 2 key: username, value: guest
depth: 2 key: password, value: guest
depth: 2 key: price, value: 100
depth: 2 key: owener, value: me

How to modify my code what can do a following example output with all datas:

depth: 0 key: authentication, value:
depth: 1 key: basic, value:
depth: 1 key: filters, 
depth: 2 key: username, value: guest
depth: 2 key: password, value: guest
depth: 2 key: price, value: 100
depth: 2 key: owener, value: me

Thank you!

like image 230
werdf02 Avatar asked Jul 02 '26 22:07

werdf02


1 Answers

When you use RecursiveIteratorIterator you can set different modes of traversing. The default one is RecursiveIteratorIterator::LEAVES_ONLY. That's why you get only leaves, but not all values (by the way array_walk_recursive has the same behavior). To visit all elements you need to set the mode to RecursiveIteratorIterator::SELF_FIRST:

$iterator = new \RecursiveIteratorIterator(
    new \RecursiveArrayIterator($array),
    \RecursiveIteratorIterator::SELF_FIRST
);

Here is working demo.

like image 128
sevavietl Avatar answered Jul 05 '26 04:07

sevavietl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!