PHP 分层数组 - 父母和孩子 [英] PHP hierarchical array - Parents and childs
本文介绍了PHP 分层数组 - 父母和孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将 PHP 和 mySQL 与 Idiorm 结合使用.这可能不相关.
I use PHP and mySQL with Idiorm. That might not be relevant.
我的 PHP 数组
- 这是父母和孩子之间的关系.
- 0 是根父级.
- 示例:根父级 0 有子级 33,子级 27 有孩子 71.
如果需要解决问题,可以更改此数组结构.
array (
33 =>
array (
0 => '27',
1 => '41',
),
27 =>
array (
0 => '64',
1 => '71',
),
0 =>
array (
0 => '28',
1 => '29',
2 => '33',
),
)
我的分层结果
类似的东西,但作为一个数组...
Something like this, but as an array...
0 =>
28
29
33
27 =>
64
71
41
信息
- 深度未知,可以是无限的.我试过 foreach,但可能不是这样.
我自己的想法
- 一些递归函数?
- 一些 while 循环?
以上两种方法我都试过了,只是一团糟.这是一个脑洞.
I tried both of the above, just got a mess. It's a brainer.
推荐答案
@deceze 的建议奏效了.然而输入数组需要改变一点,像这样......
The suggestion by @deceze worked. However the input array needs to change a litte, like this...
$rows = array(
array(
'id' => 33,
'parent_id' => 0,
),
array(
'id' => 34,
'parent_id' => 0,
),
array(
'id' => 27,
'parent_id' => 33,
),
array(
'id' => 17,
'parent_id' => 27,
),
);
来自https://stackoverflow.com/a/8587437/476:
function buildTree(array $elements, $parentId = 0) {
$branch = array();
foreach ($elements as $element) {
if ($element['parent_id'] == $parentId) {
$children = buildTree($elements, $element['id']);
if ($children) {
$element['children'] = $children;
}
$branch[] = $element;
}
}
return $branch;
}
$tree = buildTree($rows);
print_r( $tree );
这篇关于PHP 分层数组 - 父母和孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文