PHP foreach() with arrays within arrays?(PHP foreach() 与数组中的数组?)
问题描述
我想对数组中的每个元素调用一个函数.这显然很容易使用 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
这篇关于PHP foreach() 与数组中的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:PHP foreach() 与数组中的数组?
- Laravel 仓库 2022-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01