繁体   English   中英

来自mySql的二维Json输出,但有重复项

[英]Output from mySql a two dimensional Json but with duplicates

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

现在,每个位置都有一个events列表,其中包含一个或多个条目。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM