我希望我的类别列表在返回用户时格式很好。我从数据库得到的是:
[
{
"id": 1,
"name": "pet",
"parent_id": null
},
{
"id": 2,
"name": "page",
"parent_id": null
},
{
"id": 3,
"name": "dog",
"parent_id": 1
},
{
"id": 4,
"name": "cat",
"parent_id": 1
},
{
"id": 5,
"name": "rodent",
"parent_id": 1
},...
我希望它保持树形结构,如:
{
"id": 1,
"name": "pet",
"parent_id": null,
"children": [
{
"id": 3,
"name": "dog",
"parent_id": 1
},
{
"id": 4,
"name": "cat",
"parent_id": 1
},...
等
有没有一种简单的方法可以做到这一点,或者我必须遍历数据库结果并创建新的有组织的数组才能返回? 这样做的最佳方法是什么?问题是子类别也可能有子类别。或者我应该保留从数据库中获取的结构并将子ID作为数组添加(因为我可以参考它们)?
我很感激你的帮助。
谢谢。
答案 0 :(得分:0)
<强>解决方案:强>
function normalize_db_animals(){
$values[] = ["id" => 1, "name" => "pet", "parent_id" => null];
$values[] = ["id" => 2, "name" => "dog", "parent_id" => 1];
$values[] = ["id" => 3, "name" => "cat", "parent_id" => 1];
$values[] = ["id" => 4, "name" => "rodent", "parent_id" => 1];
$values[] = ["id" => 5, "name" => "wild", "parent_id" => null];
$values[] = ["id" => 6, "name" => "tiger", "parent_id" => 5];
$values[] = ["id" => 7, "name" => "rhino", "parent_id" => 5];
$normalize = function () use ($values) {
$tree = [];
$i = 0;
do {
$pet = $values[$i];
if ($pet['parent_id']) {
if (array_key_exists($pet['parent_id'], $tree)) {
$tree[$pet['parent_id']]['children'][] = $pet;
}
} else {
$tree[$pet['id']] = $pet;
}
$i++;
} while ($i < count($values));
return $tree;
};
$tree = $normalize();
echo json_encode($tree);
}
<强>结果:强>
{"1":{"id":1,"name":"pet","parent_id":null,"children":[{"id":2,"name":"dog","parent_id":1},{"id":3,"name":"cat","parent_id":1},{"id":4,"name":"rodent","parent_id":1}]},"5":{"id":5,"name":"wild","parent_id":null,"children":[{"id":6,"name":"tiger","parent_id":5},{"id":7,"name":"rhino","parent_id":5}]}}
答案 1 :(得分:0)
试试这个
$a = json_decode('[{
"id": 1,
"name": "pet",
"parent_id": null
},
{
"id": 2,
"name": "page",
"parent_id": null
},
{
"id": 3,
"name": "dog",
"parent_id": 1
},
{
"id": 4,
"name": "cat",
"parent_id": 1
},
{
"id": 5,
"name": "rodent",
"parent_id": 4
},
{
"id": 6,
"name": "rodent",
"parent_id": 2
}]');
$a = collect($a);
$filtered = $a;
foreach ($filtered as $key => $value) {
$children = $a->where('parent_id', $value->id);
if(!$children->isEmpty()){
$value->children = $children;
$filtered->forget(array_values(array_keys($children->toArray())));
}
}
dd($filtered);