Jen*_*fer 14 php arrays nested multidimensional-array
我有一个多维数组,我试图找出如何简单地"回显"数组的元素.数组的深度未知,因此可以深度嵌套.
在下面的数组的情况下,回显的正确顺序是:
This is a parent comment
This is a child comment
This is the 2nd child comment
This is another parent comment
Run Code Online (Sandbox Code Playgroud)
这是我正在谈论的数组:
Array
(
[0] => Array
(
[comment_id] => 1
[comment_content] => This is a parent comment
[child] => Array
(
[0] => Array
(
[comment_id] => 3
[comment_content] => This is a child comment
[child] => Array
(
[0] => Array
(
[comment_id] => 4
[comment_content] => This is the 2nd child comment
[child] => Array
(
)
)
)
)
)
)
[1] => Array
(
[comment_id] => 2
[comment_content] => This is another parent comment
[child] => Array
(
)
)
)
Run Code Online (Sandbox Code Playgroud)
kei*_*ant 15
看起来你只是想从每个数组中写一个重要的值.尝试像这样的递归函数:
function RecursiveWrite($array) {
foreach ($array as $vals) {
echo $vals['comment_content'] . "\n";
RecursiveWrite($vals['child']);
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以使它更具动态性,并将'comment_content'和'child'字符串作为参数传递给函数(并在递归调用中继续传递它们).
正确,更好,更清洁的解决方案:
function traverseArray($array)
{
// Loops through each element. If element again is array, function is recalled. If not, result is echoed.
foreach ($array as $key => $value)
{
if (is_array($value))
{
Self::traverseArray($value); // Or
// traverseArray($value);
}
else
{
echo $key . " = " . $value . "<br />\n";
}
}
}
Run Code Online (Sandbox Code Playgroud)
您只需在traverseArray($array)当前/主类中调用此辅助函数,如下所示:
$this->traverseArray($dataArray); // Or
// traverseArray($dataArray);
Run Code Online (Sandbox Code Playgroud)
来源:http://snipplr.com/view/10200/recursively-traverse-a-multidimensional-array/