gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:13:14 24 4
gpt4 key购买 nike

我有 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'}]}
];

最佳答案

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

$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"}]}
]
*/

关于php - 如何将对象转换为按属性分组的对象的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42908436/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com