如何在 PHP 中迭代多维数组?
我将该数据结构放入我的数组 $categories 中,
stdClass Object
(
[37] => Array
(
[term_id] => 37
[name] => Files
[parent] => 0
[38] => Array
(
[term_id] => 38
[name] => Downloads
[parent] => 37
)
)
[29] => Array
(
[term_id] => 29
[name] => Articles
[parent] => 0
[36] => Array
(
[term_id] => 36
[name] => General
[parent] => 29
)
[35] => Array
(
[term_id] => 35
[name] => WordPress
[parent] => 29
)
[34] => Array
(
[term_id] => 34
[name] => Php, Sql
[parent] => 29
)
)
[1] => Array
(
[term_id] => 1
[name] => Uncategorized
[parent] => 0
)
)
现在我喜欢做的是按以下形式打印该数据,并带有缩进。
Files
Downloads
Articles
General
WordPress
Php, Sql
Uncategorized
为了达到上述结果,我使用该代码,
$categories = get_array_content(); // Return the above data
print_category_tree($categories);
function print_category_tree(&$c)
{
foreach($c as $cat)
{
?>
<label>
<input type="checkbox" value="<?php echo $cat['term_id']; ?>" /> <?php echo $cat['name']; ?>
</label>
<br />
<?php
foreach($cat as $categ)
{
if(is_array($categ))
{
print_category_tree($categ);
}
}
}
}
我知道其中有问题,但我无法猜测是什么。有人可以帮我进行多维数组迭代吗?
I have that data structure into my array $categories
stdClass Object
(
[37] => Array
(
[term_id] => 37
[name] => Files
[parent] => 0
[38] => Array
(
[term_id] => 38
[name] => Downloads
[parent] => 37
)
)
[29] => Array
(
[term_id] => 29
[name] => Articles
[parent] => 0
[36] => Array
(
[term_id] => 36
[name] => General
[parent] => 29
)
[35] => Array
(
[term_id] => 35
[name] => WordPress
[parent] => 29
)
[34] => Array
(
[term_id] => 34
[name] => Php, Sql
[parent] => 29
)
)
[1] => Array
(
[term_id] => 1
[name] => Uncategorized
[parent] => 0
)
)
Now what I like to do is print that data in the following form with indents.
Files
Downloads
Articles
General
WordPress
Php, Sql
Uncategorized
To achive the above result I use that code
$categories = get_array_content(); // Return the above data
print_category_tree($categories);
function print_category_tree(&$c)
{
foreach($c as $cat)
{
?>
<label>
<input type="checkbox" value="<?php echo $cat['term_id']; ?>" /> <?php echo $cat['name']; ?>
</label>
<br />
<?php
foreach($cat as $categ)
{
if(is_array($categ))
{
print_category_tree($categ);
}
}
}
}
I know that something is wrong with that but I can't guess what. Can somebody please help me with multi dimentional array iteration ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 http://www.php.net/manual/en/class.recursivearrayiterator。 php
Use http://www.php.net/manual/en/class.recursivearrayiterator.php
您使用两个参数调用该函数:
但您的函数只需要一个参数:
并且您正在使用 &在函数中。您可能想在没有的情况下测试它。
You call the function with two params:
But your function takes only one param:
And you are using the & in the function. You might want to test it without.