PHP 循环遍历一个带有字符串和内部数组的数组
这是一个基本的循环问题,但有一个转折,所以我很可能错过了一些简单的东西 - 提前道歉......
我试图从数组 $testoutput 中提取结果 - 它充满了 3 个数组
:以下代码:
foreach ($testoutput as $ID => $Array) {
echo $Array . "<BR>";
}
返回:
ARRAY
ARRAY
ARRAY
使用以下代码添加第二个嵌套循环:
foreach ($testoutput as $ID => $Array) {
foreach ($Array as $ID => $L1item) {
echo $L1item . "<BR>";
}
}
结果:
String1a
String1b
String1c
ARRAY
String2a
String2b
String2c
ARRAY
String3a
String3b
String3c
ARRAY
我可以重新调整上述所有字符串,但是,我不知道如何从第三级返回值嵌套数组。
有没有简单的方法可以做到这一点?
非常感谢。
This is a basic looping question but with a twist, so it's likely that i'm missing something easy - apologies in advance...
I'm trying to pull the results from an array $testoutput - which is filled with 3 arrays:
Running the following code:
foreach ($testoutput as $ID => $Array) {
echo $Array . "<BR>";
}
Returns:
ARRAY
ARRAY
ARRAY
Adding a second nested loop with the following code:
foreach ($testoutput as $ID => $Array) {
foreach ($Array as $ID => $L1item) {
echo $L1item . "<BR>";
}
}
Results in:
String1a
String1b
String1c
ARRAY
String2a
String2b
String2c
ARRAY
String3a
String3b
String3c
ARRAY
I'm fine with retuning all of the above strings, however, I can't figure out how to return the values from the 3rd-level of nested Arrays.
Is there an easy way to do this?
Many thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(3)
风追烟花雨2024-10-06 01:00:47
试试这个:
/**
* array nested_array_map(callback $callback, array $array)
* Warning - doesn't check for recursion,
* therefore child arrays shouldn't contain references to any of parent level arrays
*
* @param $callback, function
* @param $array, array of elements to map the function to
* @return array
*/
function nested_array_map($callback, $param) {
if (!is_array($param)) {
return call_user_func($callback, $param);
}
$result = array();
foreach ($param as $index => $value) {
$result[$index] = nested_array_map($callback, $value);
}
return $result;
}
function echo_value($value) {
echo "$value\n";
return $value;
}
$test = array(
'1st level'
,array(
'2nd level'
,array(
'3rd level'
)
,'2nd level'
)
,array(
'2nd level'
)
,'1st level'
);
$result = nested_array_map('echo_value', $test);
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您可以使用
array_map
或者如果您愿意,您可以使用
array_walk_recursive
:You can use
array_map
Or if you prefer, you can use
array_walk_recursive
: