简体   繁体   English

乘法foreach递归或RecursiveIteratorIterator

[英]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 . 我的问题是:如果我使用第一个代码就可以了,或者我应该尝试使用RecursiveIteratorIterator My problem is that will be difficult to generate the exactly same structure in the second option. 我的问题是难以在第二个选项中生成完全相同的结构。 Anyway, any optimization will be nice. 无论如何,任何优化都会很好。

Have you tried any of the other constants for the mode parameter on RecursiveIteratorIterator::__construct ? 你有没有尝试过RecursiveIteratorIterator::__constructmode参数的任何其他常量? The default is RecursiveIteratorIterator::LEAVES_ONLY . 默认值为RecursiveIteratorIterator::LEAVES_ONLY

From the Docs 来自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. 也许SELF_FIRST就是你所需要的。

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

Along with the RecursiveIteratorIterator inside the foreach loop, you can use the $filter->getDepth() function to separate the child, self, and grandchild. 与foreach循环中的RecursiveIteratorIterator一起,您可以使用$filter->getDepth()函数来分隔子,self和孙。

You can also set $filter->setMaxDepth(int $depth); 你也可以设置$filter->setMaxDepth(int $depth); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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