在PHP中回显多维数组
我有一个多维数组,我试图找出如何简单地“回显”数组的元素。数组的深度未知,因此可能嵌套得很深 对于下面的阵列,正确的回波顺序为:在PHP中回显多维数组,php,arrays,multidimensional-array,nested,Php,Arrays,Multidimensional Array,Nested,我有一个多维数组,我试图找出如何简单地“回显”数组的元素。数组的深度未知,因此可能嵌套得很深 对于下面的阵列,正确的回波顺序为: This is a parent comment This is a child comment This is the 2nd child comment This is another parent comment <pre> <?php print_r ($array); ?> </pre> 这就是我所说的阵列: Arra
This is a parent comment
This is a child comment
This is the 2nd child comment
This is another parent comment
<pre>
<?php print_r ($array); ?>
</pre>
这就是我所说的阵列:
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
(
)
)
)
看起来您只是试图从每个数组中写入一个重要值。尝试如下递归函数:
function RecursiveWrite($array) {
foreach ($array as $vals) {
echo $vals['comment_content'] . "\n";
RecursiveWrite($vals['child']);
}
}
您还可以使它更具动态性,并将'comment\u content'
和'child'
字符串作为参数传递到函数中(并在递归调用中继续传递它们)。print\r($arr)
通常会给出非常可读的结果。尝试使用函数。如果要将其存储为变量,可以执行以下操作:
echo '<pre>'; print_r($array); echo '<pre/>';
recurse\u数组($value){
$content='';
if(is_数组($values)){
foreach($key=>$value的值){
if(是_数组($value)){
$content.=“$key
”。递归数组($value);
}否则{
$content.=“$key=$value
”;
}
}
}
返回$content;
}
$array\u text=递归数组($array);
显然,您可以根据需要格式化 如果输出数据是为了调试和开发目的,那么它非常适合生成易于读取的输出。请查看。递归通常是您的答案,但另一种选择是使用引用。请参见有多种方法可以做到这一点 1) -
print\r($array)代码>或如果您想要格式良好的数组,则
function recursiveFunction($array) {
foreach ($array as $val) {
echo $val['comment_content'] . "\n";
recursiveFunction($vals['child']);
}
}
合适、更好、干净的解决方案:
资料来源:这取决于你希望它被回应的顺序:广度优先还是深度优先--只是开玩笑,您已经包含了您想要的顺序。您是想将其作为向用户显示的目的,还是为了开发检查/调试数组的内容?它不是foreach($array as$elem)?:)回答得不错@埃里克·加格农:是的,你刚刚打败了我。修正了。关于字符串捕获的好主意。但是要小心循环中的连接。如果数组的大小(或深度)很大,最好使用回音,并使用ob_start()
和ob_get_clean()
正确、更好、更干净地包装函数,以检查每个值是否是数组,是否足够通用,可以处理任何嵌套数组。
function recursiveFunction($array) {
foreach ($array as $val) {
echo $val['comment_content'] . "\n";
recursiveFunction($vals['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";
}
}
}
$this->traverseArray($dataArray); // Or
// traverseArray($dataArray);