Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiples foreach recursively or RecursiveIteratorIterator

I am using this code, that works well. However seems like not the best option due the multiples foreach.

foreach ($arr_items as $key => $value) {
    $id_user = $key;
    foreach ($value as $k => $v) {
        foreach ($v as $x => $y) {
            $id_transacao = $y['id_transacao'];
            $id_duplicated = $y['id_duplicated'];
            foreach ($y as $g => $b) {
                if (is_array($b)){
                    foreach ($b as $kn => $l) {
                        var_dump($id_user);
                        var_dump($id_transacao);
                        var_dump($id_duplicated);
                        var_dump($l);
                    }
                }
            }
        }
    }
}

This code will outputs a bunch of results, probably fast, but totally disordered.

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($arr_items));

}   

My question is: It's ok if I use first code, or should I try something with the RecursiveIteratorIterator. My problem is that will be difficult to generate the exactly same structure in the second option. Anyway, any optimization will be nice.

like image 555
anvd Avatar asked Jul 10 '26 05:07

anvd


2 Answers

Have you tried any of the other constants for the mode parameter on RecursiveIteratorIterator::__construct? The default is RecursiveIteratorIterator::LEAVES_ONLY.

From the Docs

RecursiveIteratorIterator::LEAVES_ONLY - The default. Lists only leaves in iteration.
RecursiveIteratorIterator::SELF_FIRST - Lists leaves and parents in iteration with parents coming first.
RecursiveIteratorIterator::CHILD_FIRST - Lists leaves and parents in iteration with leaves coming first.

Maybe SELF_FIRST is what you need.

$iterator = new RecursiveIteratorIterator(
                new RecursiveArrayIterator($arr_items), 
                RecursiveIteratorIterator::SELF_FIRST);
like image 76
quickshiftin Avatar answered Jul 13 '26 14:07

quickshiftin


Along with the RecursiveIteratorIteratorinside the foreach loop, you can use the $filter->getDepth() function to separate the child, self, and grandchild.

You can also set $filter->setMaxDepth(int $depth);.

like image 44
Tuhin Bepari Avatar answered Jul 13 '26 14:07

Tuhin Bepari



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!