librium librium - 4 months ago 12
JSON Question

How to remove duplicates from json in PHP

I have a MySQL, PHP code as follows.

$sql = "SELECT * FROM shipschedule WHERE ship_date BETWEEN '2016-08-01' AND '2016-8-31'";
$result = $mysqli->query($sql);
$e = array();

while($r = $result->fetch_array()) {
$rows = array();
$rows['title'] = $r['title'];
$rows['start'] = $r['ship_date'];
array_push($e, $rows);
}
echo json_encode($e);


The above php code echos

[{"title":"111","start":"2016-08-10"},
{"title":"111","start":"2016-08-10"},
{"title":"111","start":"2016-08-10"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]


My question is how I can echo the above as follow instead. Please see that duplicate start dates will be removed by title.

[{"title":"111","start":"2016-08-10"},
{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]


title 111 has the same 3 start dates, and I need to display it like

{"title":"111","start":"2016-08-10"},


title 222 has the same 2 start dates, and I need to display it like

{"title":"222","start":"2016-08-17"},
{"title":"222","start":"2016-08-16"}]

Answer

You could prevent receiving duplicates, and reduce requesting unnecessary data by adjusting your query.

SELECT DISTINCT title, start FROM ...