我有这个数组:
$arr = [
["id"=>20,
"name"=>"a",
"parent"=>28,
],
["id"=>21,
"name"=>"a-child",
"parent"=>20,
],
["id"=>27,
"name"=>"a-child-b",
"parent"=>20,
],
["id"=>28,
"name"=>"A parent",
"parent"=>0,
],
["id"=>12,
"name"=>"no parent",
"parent"=>0,
]];
我想要的是基于parent
键对其进行分组,如果父键大于零,则其中parent = id && parent > 0
或是id
该元素的父元素,并且该元素具有父元素。
在上面的数组id=12
中,没有父项,id=20
有子项21, 27
,并且是的子项id=28
。
我做了什么 :
public function sort($arr){
$result = [];
// Get child
foreach($arr as $key => $row) {
if($row['parent'] > 0) {
$result[$row->parent][] = ['id' => $row['id'], 'name' => $row['name']];
unset($arr[$key]);
}
}
// Get parent and append child
foreach($arr as $key => $row) {
$result[$row['id']] = ['name' => $row['name'],
'child' => $result[$row['id']]];
}
return $result;
}
问题是,这仅适用于1级孩子parent => child array()
。
我想做的是一个获取参数(在数组上方)的方法,我不知道我将拥有多少层嵌套并parent
按键数组分组返回结果:
$arr = [
["id"=>28,
"name"=>"A parent",
"parent"=>0,
'child' => [
["id"=>20,
"name"=>"a",
"parent"=>28,
'child' => [
["id"=>21,
"name"=>"a-child",
"parent"=>20,
],
["id"=>27,
"name"=>"a-child-b",
"parent"=>20,
]
]
]
]
],
["id"=>12,
"name"=>"no parent",
"parent"=>0,
]];
<?php
define('ROOT_PARENT',0);
function getHierarchy($records){
$hierarchy = [];
/*
let's assume everybody is going to be a parent
*/
foreach($records as $each_record){
$each_record['child'] = [];
$hierarchy[$each_record['id']] = $each_record;
}
/*
Now add child to parent's key in $hierarchy in the 'child' key.
The & is important since there may be future childs for current child. So pass by reference is needed
*/
foreach($records as $each_record){
$hierarchy[$each_record['parent']]['child'][] = &$hierarchy[$each_record['id']];
}
/*
here I unset every key which wasn't at root level,i.e is 0(top) level
*/
foreach($hierarchy as $parent => $its_data){
if($parent != ROOT_PARENT){
unset($hierarchy[$parent]);
}
}
return isset($hierarchy[ROOT_PARENT],$hierarchy[ROOT_PARENT]['child']) ? $hierarchy[ROOT_PARENT]['child'] : [];
}
$records = [
[
"id" => 20,
"name" => "a",
"parent" => 28,
],
[
"id" => 21,
"name" => "a-child",
"parent" => 20,
],
[
"id" => 27,
"name" => "a-child-b",
"parent" => 20,
],
[
"id" => 28,
"name" => "A parent",
"parent" => 0,
],
[
"id" => 12,
"name" => "no parent",
"parent" => 0,
]
];
echo "<pre>";
print_r(getHierarchy($records));
输出:
Array
(
[0] => Array
(
[id] => 28
[name] => A parent
[parent] => 0
[child] => Array
(
[0] => Array
(
[id] => 20
[name] => a
[parent] => 28
[child] => Array
(
[0] => Array
(
[id] => 21
[name] => a-child
[parent] => 20
[child] => Array
(
)
)
[1] => Array
(
[id] => 27
[name] => a-child-b
[parent] => 20
[child] => Array
(
)
)
)
)
)
)
[1] => Array
(
[id] => 12
[name] => no parent
[parent] => 0
[child] => Array
(
)
)
)
首先,我们认为每个人都可以是父母。然后,在它的父母的child
钥匙中,我们继续添加它的孩子。key
由于可能会有未来的孩子,我们通过了引用。最后,unset()
来自层次结构的不是根父级的每个人。最后,您将拥有最终的层次结构。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句