mySql 输出如下:
正如您所看到的,第 3 行和第 4 行有重复项,因此我想在输出 Json 时合并这些重复项。确切地说,我希望我的 json 是这样的:
[
{
"name": "The Crane Bar",
"lat": "53.2692",
"lng": "-9.06151",
"events": [
{
"name": "Traditional music session",
"info": null
}
]
},
{
"name": "Taaffes Bar",
"lat": "53.2725",
"lng": "-9.05321",
"events": [
{
"name": "6 Nations, Italy VS Ireland",
"info": null
}
]
},
{
"name": "a house",
"lat": "37.4401",
"lng": "-122.143",
"events": [
{
"name": "Party at Palo Alto",
"info": "Some info about the party"
},
{
"name": "2gdfgdf",
"info": "2gdfgdfgdf"
}
]
}
]
您知道使用一一的 location_name、lat 和 lng,并且嵌套了 event_name 和 post_content(如此处的信息)。
谢谢!
最佳答案
根据您的评论,您希望结果是嵌套的,因此当您生成 JSON 时,迭代行并在 PHP 中构建嵌套结果列表:
$result = array();
$item = null;
for ($i = 0; $i < count($rows); ++$i) {
$row = $rows[$i];
if ($item === null) {
$item = array('location' => $row['location'], 'events' => array());
}
$item['events'][] = array('name' => $row['event_name']);
if ($i == count($rows) - 1 || $row['location'] != $rows[$i + 1]['location']) {
$result[] = $item;
$item = null;
}
}
echo json_encode($result); // JSON-encoded data
现在,每个位置都会有一个包含一个或多个条目的事件
列表。
关于php - mySql 的输出是二维 Json 但有重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13221310/