如何从PHP中删除json中的重复项

时间:2016-08-04 20:48:55

标签: php mysql json

我有一个MySQL,PHP代码如下。

$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);

上面的php代码回声

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

我的问题是我如何回应上面的内容,而不是如下。请注意,重复的开始日期将按标题删除。

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

标题111具有相同的3个开始日期,我需要将其显示为

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

标题222具有相同的2个开始日期,我需要将其显示为

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

2 个答案:

答案 0 :(得分:3)

您可以阻止接收重复项,并通过调整查询来减少请求不必要的数据。

SELECT DISTINCT title, start FROM ...

答案 1 :(得分:2)

从MySQL获取正确(唯一)数据会更容易(也可能更快)。这可以通过distinct修饰符来实现:

SELECT DISTINCT title, start
FROM   shipschedule
WHERE  ship_date BETWEEN '2016-08-01' AND '2016-8-31'