php печать json вывод данных в группу - PullRequest
1 голос
/ 04 мая 2020

У меня есть эти выходные данные из базы данных:

Array

(
    [0] => stdClass Object
        (
            [name] => attr one
            [attribute_id] => 1
            [attribute_group] => group one
            [attribute_group_id] => 1
        )

    [1] => stdClass Object
        (
            [name] => attr two
            [attribute_id] => 2
            [attribute_group] => group one
            [attribute_group_id] => 1
        )

    [2] => stdClass Object
        (
            [name] => attr three
            [attribute_id] => 3
            [attribute_group] => group one
            [attribute_group_id] => 1
        )

    [3] => stdClass Object
        (
            [name] => attr four
            [attribute_id] => 4
            [attribute_group] => group two
            [attribute_group_id] => 2
        )

)

теперь для json выход:

    foreach ($results as $result) {
        $json[] = array(
            'id' => $result->attribute_group_id,
            'text' => $result->attribute_group,
            'children' => [array(
                'id' => $result->attribute_id,
                'text' => $result->name,
            )]
        );
    }
    return json_encode($json);

вывод:

[
   {
      "id":"1",
      "text":"group one",
      "children":[
         {
            "id":"1",
            "text":"attr one"
         }
      ]
   },
   {
      "id":"1",
      "text":"group one",
      "children":[
         {
            "id":"2",
            "text":"attr two"
         }
      ]
   },
   {
      "id":"1",
      "text":"group one",
      "children":[
         {
            "id":"3",
            "text":"attr three"
         }
      ]
   },
   {
      "id":"2",
      "text":"group two",
      "children":[
         {
            "id":"4",
            "text":"attr four"
         }
      ]
   }
]

Но в Действие Мне нужно вывести данные, сгруппированные по attribute_group и перечисленные в children следующим образом:

[
   {
      "id":"1",
      "text":"group one",
      "children":[
         {
            "id":"1",
            "text":"attr one"
         },
            "id":"2",
            "text":"attr two"
         },
         {
            "id":"3",
            "text":"attr three"
         }
      ]
   },
   {
      "id":"2",
      "text":"group two",
      "children":[
         {
            "id":"4",
            "text":"attr four"
         }
      ]
   }
]

как мне создать этот вывод json?!

1 Ответ

2 голосов
/ 04 мая 2020

Вместо создания массива $ json с элементом для каждого атрибута, вы должны собирать каждый атрибут напрямую по attribute_group_id.

Для этого идея состоит в том, чтобы использовать attribute_group_id в качестве ключа вашего массива $ json ($ json [$ result-> attribute_group_id]). Если для $ json [$ result-> attribute_group_id] ['children'] уже существует запись, то вам просто нужно иметь текущих дочерних элементов для этого элемента. Если нет, вы создаете запись для текущего идентификатора группы атрибутов с его информацией (id, text, children).

Наконец, вы можете вернуть $ json без ключа, который мы использовали для группировки атрибутов, используя array_values ​​(возвращает значения массива без ключей).

foreach ($results as $result) {  
    if(isset($json[$result->attribute_group_id]['children'])){
        $json[$result->attribute_group_id]['children'][] = array(
            'id' => $result->attribute_id,
            'text' => $result->name,
        );
    }
    else {
        $json[$result->attribute_group_id] = array(
            'id' => $result->attribute_group_id,
            'text' => $result->attribute_group,
            'children' => [array(
                'id' => $result->attribute_id,
                'text' => $result->name,
            )]
        );
    }
}

return json_encode(array_values($json));

Результат:

[
  {
    "id": "1",
    "text": "group one",
    "children": [
      {
        "id": "1",
        "text": "attr one"
      },
      {
        "id": "2",
        "text": "attr two"
      },
      {
        "id": "3",
        "text": "attr three"
      }
    ]
  },
  {
    "id": "2",
    "text": "group two",
    "children": [
      {
        "id": "4",
        "text": "attr four"
      }
    ]
  }
]
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...