我们有一个随机类别列表,需要按照以下规则在JSON输出中进行排列- 一种。所有父类别应按字母顺序排序 b。每个父类别都应按字母顺序对其子类别进行排序 C。亲子关系可以是多层次的
deiconify
答案 0 :(得分:0)
此代码将假定父级出现在子级元素之前。它将没有父ID的所有内容添加到输出数组($out
)的基中,否则调用递归函数addChild()
。 (忘记了,所以添加了)将每个条目添加到现有子项时,它使用usort()
来按字母顺序对条目进行排序。
这将检查每个节点并检查它是否是父节点,如果不是,还将检查该节点的任何子节点(如果有),等等...
function addChild ( $element, &$tree ) {
foreach ( $tree as &$leaf ) {
if ( $leaf['_id'] == $element['parent'] ) {
$leaf['children'][] = $element;
usort($leaf['children'],
function($a, $b) {
return strcmp($a["name"], $b["name"]);
});
break;
}
if ( isset($leaf['children']) ) {
addChild($element, $leaf['children']);
}
}
}
$out = [];
foreach ( $data as $element ) {
if ( empty($element['parent']) ) {
$out[] = $element;
}
else {
// Look for parent
addChild($element, $out);
}
}
创建...
Array
(
[0] => Array
(
[name] => Travel
[parent] =>
[_id] => 1
[children] => Array
(
[0] => Array
(
[name] => Air Travel
[parent] => 1
[_id] => 1212
[children] => Array
(
[0] => Array
(
[name] => Insurance
[parent] => 1212
[_id] => 113412
)
)
)
[1] => Array
(
[name] => Hotel
[parent] => 1
[_id] => 212
)
)
)
[1] => Array
(
[name] => Businss Exp
[parent] =>
[_id] => 2
[children] => Array
(
[0] => Array
(
[name] => Taxes
[parent] => 2
[_id] => 34
[children] => Array
(
[0] => Array
(
[name] => Licenses
[parent] => 34
[_id] => 111232
)
[1] => Array
(
[name] => Local Tax
[parent] => 34
[_id] => 34111
)
)
)
)
)
)