简体   繁体   中英

PHP Returning JSON with modified data

I want my categories list be nice formatted while return to user. What I get from database is:

[
{
    "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
},...

I want it to keep tree structure, like:

{
    "id": 1,
    "name": "pet",
    "parent_id": null,
    "children": [
        {
            "id": 3,
            "name": "dog",
            "parent_id": 1
        },
        {
            "id": 4,
            "name": "cat",
            "parent_id": 1
        },...

etc.

Is there an easy way way to do it or I have to loop through the database results and create new organized array to return? What is the best approach to do that? The problem is that the subcategories could also have subcategories. Or maybe i should just keep structure I get from the database and add children id's as an array (as I can refer to them anyway)?

I would be grateful for your help.

Thank you.

Solution:

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

Result:

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

Try this one

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM