PHP:遍历数组?
- 我想要一个函数 搜索我的数组,并且 返回所有 子节点到特定节点。什么是 最合适的方法是这样做? 在这种情况下需要递归吗?
我之前构建了一些相当复杂的函数,这些函数在有或没有递归的帮助下通过多维数组进行迭代并重新排列它们,但是这个问题让我完全陷入困境,我不能只是解决它......
这是我的数组:
Array
(
[1] => Array (
[id] => 1
[parent] => 0
)
[2] => Array (
[id] => 2
[parent] => 1
)
[3] => Array (
[id] => 3
[parent] => 2
)
)
更新:
我想要获得的输出。抱歉这个不好的例子,但我会把它归咎于缺乏如何格式化我需要做的事情的知识:)
function getAllChildren($id) {
// Psuedocode
return $array;
}
getAllChildren(1); // Outputs the following:
Array
(
[2] => Array (
[id] => 2
[parent] => 1
)
[3] => Array (
[id] => 3
[parent] => 2
)
)
- I want a function that
searches through my array, and
returns all the
children to a specific node. What is
the most appropriate way to do this?
Will recursion be necessary in this case?
I have previously constructed a few quite complex functions that iterates with or without the help of recursion through multi-dimensional arrays and re-arranging them, but this problem makes me completely stuck and I can't just get my head around it...
Here's my array:
Array
(
[1] => Array (
[id] => 1
[parent] => 0
)
[2] => Array (
[id] => 2
[parent] => 1
)
[3] => Array (
[id] => 3
[parent] => 2
)
)
UPDATE:
The output which I want to get. Sorry for the bad example, but I'll blame it on lack of knowledge on how to format the stuff I need to do :)
function getAllChildren($id) {
// Psuedocode
return $array;
}
getAllChildren(1); // Outputs the following:
Array
(
[2] => Array (
[id] => 2
[parent] => 1
)
[3] => Array (
[id] => 3
[parent] => 2
)
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
searchItem() 函数的非递归版本:(
假设父节点/子节点的顺序,因此子节点不会包含在数组中,除非父节点已经存在)
Non-recursive version of the searchItem() function:
(assumes ordering of the parents/children, so a child node isn't included in the array unless the parent is already there)
查看 PHP 中的
array_walk_recursive()
函数:http://www.php.net/manual/en/function.array-walk-recursive.php
Check out the
array_walk_recursive()
function in PHP:http://www.php.net/manual/en/function.array-walk-recursive.php