Diolor
Diolor

Reputation: 13450

Output from mySql a two dimensional Json but with duplicates

mySql outputs this: enter image description here

As you can see row 3 and 4 has duplicates so I want to merge these duplicates when I output my Json. To be exact I want my json to be like this:

[
    {
        "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"
            }
        ]
    }
]

You know use one one location_name, lat and lng and have nested the event_name and post_content (as info here).

Thanks!

Upvotes: 0

Views: 516

Answers (1)

jspcal
jspcal

Reputation: 51904

Based on your comment, you want the results to be nested, so when you generate the JSON, iterate over the rows and build a nested result list in 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

Now each location will have an events list with one or more entries.

Upvotes: 1

Related Questions