如何将对象转换为按属性分组的对象?

时间:2017-03-20 16:04:34

标签: php mysql

我有MySQL表

mysql> DESCRIBE tag;
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+
| id    | tinyint(3)  | NO   | PRI | NULL    | auto_increment |
| title | tinyint(3)  | NO   | MUL | NULL    |                |
| name  | varchar(50) | NO   |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

我做了基本的SELECT * FROM tag查询,它会给我一些类似的东西:

| id | title | name                |
+----+-------+---------------------+
| 19 |    5 | name1         |
| 20 |    5 | name2         |
| 21 |    6 | name3         |
| 22 |    6 | name4         |

我需要的是在JS JSON中接收,以便id和名称按标题分组。我的意思是我可以做一些像(有角度的):

<div ng-repeat="title in data">
   <span ng-repeat="name in title">
...

我在寻找php / mysql解决方案。到目前为止,已经尝试了很多难看的变化而没有运气。当然应该有一个很好的方法,如果有人可以提供帮助,我将不胜感激。

更新 这是我需要从服务器获取的JSON结构:

[
    {title: '5', tags:[{id: 19, name: 'name1'}, {id: 20, name: 'name2'}]},
    {title: '6', tags:[{id: 21, name: 'name3'}, {id: 22, name: 'name4'}]}
];

1 个答案:

答案 0 :(得分:0)

一种解决方案是循环结果并将它们添加到新数组中:

$rows = [
    [
        'id' => 19,
        'title' => 5,
        'name' => 'name1'
    ],
    [
        'id' => 20,
        'title' => 5,
        'name' => 'name2'
    ],
    [
        'id' => 21,
        'title' => 6,
        'name' => 'name3'
    ],
    [
        'id' => 22,
        'title' => 6,
        'name' => 'name4'
    ],
];

$sorted = [];
foreach($rows as $row) {
    $sorted[$row['title']][] = [
        'id' => $row['id'],
        'name' => $row['name'],
    ];
}

var_dump($sorted);
/*
array (size=2)
  5 => 
    array (size=2)
      0 => 
        array (size=2)
          'id' => int 19
          'name' => string 'name1' (length=5)
      1 => 
        array (size=2)
          'id' => int 20
          'name' => string 'name2' (length=5)
  6 => 
    array (size=2)
      0 => 
        array (size=2)
          'id' => int 21
          'name' => string 'name3' (length=5)
      1 => 
        array (size=2)
          'id' => int 22
          'name' => string 'name4' (length=5)
*/

echo json_encode($sorted);
// {"5":[{"id":19,"name":"name1"},{"id":20,"name":"name2"}],"6":[{"id":21,"name":"name3"},{"id":22,"name":"name4"}]}

修改

根据您的预期输出,我通过第二个foreach循环抛出数组:

$output = [];
foreach($sorted as $title => $row) {
    $output[] = [
        'title' => $title,
        'tags' => $row,
    ];
}

echo json_encode($output);
/*
[
    {"title":5,"tags":[{"id":19,"name":"name1"},{"id":20,"name":"name2"}]},
    {"title":6,"tags":[{"id":21,"name":"name3"},{"id":22,"name":"name4"}]}
]
*/