我想轉換下面的平面陣列:
$array = [
[
"hierarchy" => "1",
"title" => "Fruits",
"type" => "category_label"
],
[
"hierarchy" => "1.1",
"title" => "Citruses",
"type" => "category_label"
],
[
"hierarchy" => "1.1.1",
"title" => "Orange",
"type" => "item"
],
[
"hierarchy" => "1.1",
"title" => "Mango",
"type" => "item"
],
[
"hierarchy" => "1.2",
"title" => "Grape",
"type" => "item"
]
];
從上面可以看出,它有兩個分層的點符號字串“1.1”,因此我使用“type”屬性來區分它們。
我期待的結果是什么:
/*
1. Fruits
- 1.1. Citruses
--- 1.1.1. Orange
-- 1.1. Mango
-- 1.2. Grape
*/
//Desired result
[
"hierarchy" => "1",
"title" => "Fruits",
"type" => "category_label",
"children" => [
[
"hierarchy" => "1.1",
"title" => "Citruses",
"type" => "category_label"
"children" => [
[
"hierarchy" => "1.1.1",
"title" => "Orange",
"type" => "item"
]
]
],
[
"hierarchy" => "1.1",
"title" => "Mango",
"type" => "item"
],
[
"hierarchy" => "1.2",
"title" => "Grape",
"type" => "item"
]
]
];
使用How to build a tree from a concatenated string in PHP? 中描述的方法。我無法達到我想要的結果。我現在能做什么?
uj5u.com熱心網友回復:
您可以首先在新的關聯陣列中按層次結構鍵入所有專案。然后再次迭代這些項,并洗掉 的最后一部分hierarchy以獲取父項的鍵,將其定位在新的關聯陣列中,并將其添加到其子項中。如果它沒有父級,則將其添加到結果陣列中。
由于您的hierarchy分隔符是一個點,您可以使用該pathinfo函式從中洗掉最后一個“擴展名”:
事實證明,您的層次結構編號不是唯一的(例如“1.1”)。如果打算父節點可以與“item”型別的兄弟節點具有相同的編號,但相同型別的兩個節點永遠不會具有相同的層次結構,則通過型別和層次結構的組合來鍵入節點:
foreach ($array as $item) $keyed[$item["type"] . $item["hierarchy"]] = $item;
foreach ($keyed as &$item) {
$parent = pathinfo($item["hierarchy"], PATHINFO_FILENAME);
if ($parent == $item["hierarchy"]) $result[] =& $item;
else $keyed["category_label$parent"]["children"][] =& $item;
}
運行后,$result將具有所需的結構。
但是,我建議使層次結構代碼唯一,這樣它們就不會在型別之間發生沖突。那么上面的代碼可以改成:
foreach ($array as $item) $keyed[$item["hierarchy"]] = $item;
foreach ($keyed as &$item) {
$parent = pathinfo($item["hierarchy"], PATHINFO_FILENAME);
if ($parent == $item["hierarchy"]) $result[] =& $item;
else $keyed[$parent]["children"][] =& $item;
}
uj5u.com熱心網友回復:
看看這個邏輯是否有幫助,我會嘗試在 1 天內編輯答案并解釋。
$tree_array = [];
foreach($array as $key => $value){
if(count(explode('.',$value['hierarchy']) == 1){
array_push($array_tree, $value)
}
}
foreach($array as $value){
if(count(explode('.',$value['hierarchy'])) == 2){
if($value['type'] == 'category_label'){
foreach($array_tree as $key => $tree){
if($tree['hierarchy'] == explode('.',$value['hierarchy'])[0]){
array_push($array_tree['children'],$value);
}
}
} else {
foreach($array_tree as $key => $tree){
if($tree['hierarchy'] == explode('.',$value['hierarchy'])[0]){
array_push($array_tree[$key],$value);
}
}
}
}
}
foreach($array as $value){
if(count(explode('.',$value['hierarchy'])) == 3){
if($value['type'] == 'item'){
foreach($array_tree as $key => $tree){
foreach($tree as $item){
if($item['hierarchy'] == explode('.',$value['hierarchy'],2)[1]){
array_push($array_tree[$key]['children'],$value);
}
}
}
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/334120.html
