PHP foreach() 在数组中包含数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5524227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP foreach() with arrays within arrays?
提问by Bojangles
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.
我想对数组中的每个元素调用一个函数。使用 a 显然很容易foreach()
,但我开始分解的地方是数组包含数组时。有人可以帮我解决一个函数,该函数将为数组中的一组数组中的每个键 -> 值对执行一些代码。理论上,深度可以是无限的,但如果递归不起作用,一个好的限制是 3 次迭代(数组中的数组中的数组)。
An example array would be one taken from $_POST below:
一个示例数组是从下面的 $_POST 中获取的一个:
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
詹姆士
回答by Gordon
That's a perfect job for Iterators:
这是Iterators的完美工作:
$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach($iterator as $key => $value) {
echo "$key => $value\n";
}
See Introduction to SPL Iteratorsand Live Demo on codepad
EDIT:the alternative would be array_walk_recursive
as show in Finbarr's answer below
回答by Finbarr
See array_walk_recursive- a PHP library function that recursively calls a user defined function against a provided array.
请参阅array_walk_recursive- 一个 PHP 库函数,它针对提供的数组递归调用用户定义的函数。
From PHP docs:
来自 PHP 文档:
<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
function test_print($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($fruits, 'test_print');
?>
Output:
输出:
a holds apple
b holds banana
sour holds lemon
Note that Any key that holds an array will not be passed to the function.
.
请注意Any key that holds an array will not be passed to the function.
。
EDIT: slightly less ugly example:
编辑:稍微不那么难看的例子:
<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
array_walk_recursive($fruits, function ($item, $key) {
echo "$key holds $item\n";
});
?>
回答by Pascal MARTIN
Typically, in this kind of situation, you'll have to write a recursive function-- which will deal with an item if it's not an array ; and call itself on an item if it's an array.
通常,在这种情况下,您必须编写一个递归函数——如果它不是数组,它将处理一个项目;如果它是一个数组,则在一个项目上调用自己。
Here, you could have something like this :
在这里,你可以有这样的事情:
$arr = array(
'languages' => array(
'php', 'mysql', 'inglip',
),
'rates' => array(
'incall' => array('1hr' => 10),
'outcall' => array('1hr' => 10),
),
);
function recurse($item) {
foreach ($item as $key => $value) {
if (is_array($value)) {
recurse($value);
} else {
echo "$key : $value\n";
}
}
}
And calling this recursive function on your array :
并在您的数组上调用此递归函数:
recurse($arr);
Would get you :
会让你:
0 : php
1 : mysql
2 : inglip
1hr : 10
1hr : 10
回答by Jon
Here's a simple reusable implementation:
这是一个简单的可重用实现:
function recursive_foreach($array, $callback) {
foreach($array as $key => $value) {
if (is_array($value)) {
recursive_foreach($value, $callback);
}
else {
call_user_func($callback, $key, $value);
}
}
}
Where $callback
is a callback accepting two arguments: key and value. For example:
$callback
接受两个参数的回调在哪里:键和值。例如:
recursive_foreach($array, function($k, $v) {
echo "$k => $v<br>";
});
回答by Josh Davis
I want to call a function on each element in an array. This is obviously very easy with a foreach()
我想对数组中的每个元素调用一个函数。使用 foreach() 显然很容易
If you want to run a function on every element of a deep array, you can use array_walk_recursive()
如果要对深数组的每个元素运行一个函数,可以使用array_walk_recursive()
array_walk_recursive($array, function($v, $k)
{
echo "$k => $v\n";
});
If you want to iterate over each element with foreach
, you need a recursive iterator as mentionned previously.
如果你想用 迭代每个元素foreach
,你需要一个前面提到的递归迭代器。
If you're not sure which one to use, go with foreach
+ recursive iterator. It's easier to grasp for most people.
如果您不确定要使用哪个,请使用foreach
+ 递归迭代器。大多数人更容易掌握。
回答by thaolt
function getEndNodes($input, $ret = array()) {
foreach ($input as $key => $value) {
if (!is_array($input[$key])) {
$ret[$key] = $value;
} else {
$ret = getEndNodes($input[$key],$ret);
}
}
return $ret;
}
// Usage:
$endNodes = getEndNodes($yourarray);
回答by bicccio
function traverseArray($array)
{
foreach($array as $key=>$value)
{
if(is_array($value))
{
traverseArray($value);
}else{
echo '['.$key.']'.' => '.$value.'<br />\n';
}
}
}
回答by Marc B
function array_spelunk($array = array()) {
foreach($array as $key => $node) {
if (is_array($node)) {
array_spelunk($node);
} else {
echo "[$key] [$node]\n";
}
}
}
array_spelunk($your_nested_array);
回答by Emil Vikstr?m
function recurse($element, $key = null) {
if(is_array($element)) {
foreach($element as $k => $v) {
recurse($v, $k);
}
}else{
//Do what you want here. $element is value, $key is the key
}
}