php - mySql 的输出是二维 Json 但有重复项

标签 php mysql json multidimensional-array duplicates

mySql 输出如下: enter image description here

正如您所看到的,第 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/

相关文章:

php - Codeigniter 3.1 IFNULL 和 Coalesce 不起作用?

php - PHP/MySQL 搜索引擎的 session 问题

php - 如何在 PHP 中获取不存在文件的规范化路径(真实路径)?

mysql - sql 查询 : show name with all vowels

jquery - 从 jquery 中的 json 中提取部分

php - 如何在 Typo3 file.inc 中链接自己的 css/php 文件

php - MySQL、Python - Latin-1/UTF8 编码

PHP + MySQL + HTML 在表格中显示不同的信息

javascript - 如何将字符串转换为字典数组

javascript - 如何在 jQuery append 中输出图片链接