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() 与数组中的数组?
基础教程推荐
- 在多维数组中查找最大值 2021-01-01
- Libpuzzle 索引数百万张图片? 2022-01-01
- 如何在 PHP 中的请求之间持久化对象 2022-01-01
- 在 Woocommerce 中根据运输方式和付款方式添加费用 2021-01-01
- 超薄框架REST服务两次获得输出 2022-01-01
- 在 PHP 中强制下载文件 - 在 Joomla 框架内 2022-01-01
- 通过 PHP SoapClient 请求发送原始 XML 2021-01-01
- WooCommerce 中选定产品类别的自定义产品价格后缀 2021-01-01
- XAMPP 服务器不加载 CSS 文件 2022-01-01
- mysqli_insert_id 是否有可能在高流量应用程序中返回 2021-01-01