PHP foreach() 与数组中的数组?

2022-01-24 00:00:00 arrays iteration php

我想对数组中的每个元素调用一个函数.这显然很容易使用 foreach(),但我开始分解的地方是数组包含数组的时候.有人可以帮我解决一个函数,该函数将为数组中的一组数组中的每个键-> 值对执行一些代码.理论上,深度可以是无限的,但如果递归不起作用,一个好的限制是 3 次迭代(数组中的数组).

一个示例数组将取自下面的 $_POST:

<上一页>大批([语言] => 数组([0] => php[1] => mysql[2] => 英利普)[费率] => 数组([调用] => 数组([1 小时] => 10)[outcall] => 数组([1 小时] => 10)))

只是为了确保,我想要做的是运行一段代码(一个函数),它会传递给数组结构中的每个结束节点",所以在上面的示例中,它将在...

<上一页>[0] => php[1] => mysql[2] => 英利普[1 小时] => 10[1 小时] => 10

...找到了.

感谢您的帮助,

詹姆斯

解决方案

这对 迭代器:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));foreach($iterator as $key => $value) {echo "$key => $value
";}

请参阅 SPL 迭代器简介 和 键盘现场演示

替代方案是 array_walk_recursive 如下面 Finbarr 的回答所示

I want to call a function on each element in an array. This is obviously very easy with a foreach(), but where I start breaking down is when arrays contain arrays. Can someone help me out with a function that will execute some code for every key -> value pair from a set of arrays within arrays. The depth could, in theory, be infinite, but a good limit would be 3 iterations (array in array in array) if recursion couldn't work.

An example array would be one taken from $_POST below:

Array
(
    [languages] => Array
    (
        [0] => php
        [1] => mysql
        [2] => inglip
    )

    [rates] => Array
    (
        [incall] => Array
        (
            [1hr] => 10
        )

        [outcall] => Array
        (
            [1hr] => 10
        )

    )
)

Just to make sure, what I want to do is run a piece of code (a function) that is passed every 'end node' in the array structure, so in the example above, it would be called when...

[0] => php
[1] => mysql
[2] => inglip
[1hr] => 10
[1hr] => 10

... is found.

Thanks for any help,

James

解决方案

That's a perfect job for Iterators:

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key => $value) {
    echo "$key => $value
";
}

See Introduction to SPL Iterators and Live Demo on codepad

EDIT: the alternative would be array_walk_recursive as show in Finbarr's answer below

相关文章