PHP的foreach()与数组内的数组? [英] PHP foreach() with arrays within arrays?

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

问题描述

我想打电话给每个元素的功能在数组中。这显然​​是很容易用的foreach(),但在那里我开始打破时数组包含数组。有人可以帮助我将执行一些code为每个键的功能 - >从一组阵列内的阵列值对。深度在理论上,是无限的,但良好的限制是3次迭代(在阵列阵列阵列)如果递归不能工作。

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.

一个例子阵列会从下面$ _ POST采取之一:

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
        )

    )
)

只是为了确保,我想要做的是运行一块是在阵列结构通过每一个结束节点code(函数),所以在上面的例子中,它会被调用时...

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.

感谢您的帮助,

詹姆斯

推荐答案

这对迭代器

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

请参阅介绍SPL迭代器并的在codePAD 现场演示

编辑:的选择将是<一个href=\"http://stackoverflow.com/questions/5524227/php-foreach-with-arrays-within-arrays/5524307#5524307\"><$c$c>array_walk_recursive作为显示在下面财务巴雷答案

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

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

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