【问题标题】:PHP Returning JSON with modified dataPHP返回带有修改数据的JSON
【发布时间】:2017-11-26 05:04:54
【问题描述】:

我希望我的类别列表在返回给用户时具有良好的格式。我从数据库中得到的是:

[
{
    "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 作为数组添加(无论如何我都可以引用它们)?

感谢您的帮助。

谢谢。

【问题讨论】:

  • 由于您描述的关系不是以数据类型的形式内置于 php 中的,因此您必须自己创建树结构。仅仅是因为你必须描述构建它的算法。
  • 我正在使用 lumen (laravel) 框架(其中的新手)。可以在类别模型中构建吗?
  • 我们能看到你的控制器中返回那个的代码吗?
  • 是的,但是为什么? :P $categories = response()->json(Category::all());或 $categories = DB::table('categories')->get();两者都给出相同的响应。

标签: php json laravel laravel-5 lumen


【解决方案1】:

解决方案:

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}]}}

【讨论】:

  • 如果有例如,这个将不起作用。猫或狗类别(并且会有)
  • 我没看懂你的回答,能不能多给点启发?如果您将其称为嵌套类别,例如:猫和狗,作为父类别,您应该细化寻找递归的解决方案。将闭包封装到这个函数中(array_walk_recursive):php.net/manual/en/function.array-walk-recursive.php
  • 或者进行传统的递归回调传递: normalize_db_animals($branch),其中 $branch 可以是当前迭代标记的子数组,并声明一个不断推送所需数据的 $normalized_tree 数组。您应该在里面注释 json_encode() 并返回 $tree。当心父母和孩子的名字和分类相同,也许你应该添加另一个属性,如 uuid。
【解决方案2】:

试试这个

$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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 2018-02-16
    • 1970-01-01
    • 2021-03-11
    相关资源
    最近更新 更多