PHP foreach() 在数组中包含数组? [英] PHP foreach() with arrays within arrays?

查看:35
本文介绍了PHP foreach() 在数组中包含数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

一个示例数组是从下面的 $_POST 中获取的一个:

<前>大批([语言] => 数组([0] => php[1] => mysql[2] => 英唇)[费率] => 数组([incall] => 数组([1 小时] => 10)[外呼] => 数组([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\n";}

请参阅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\n";
}

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

这篇关于PHP foreach() 在数组中包含数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆