-4

我的 PHP 脚本正在返回一些数组,我想删除该数组中的重复项。你能告诉我怎么做吗?我不想从 MySQL 中删除重复项,只是从 PHP 中删除。我看到了一些与此类似的问题,但我找不到实现答案的方法。

我的PHP:

$con = mysqli_connect($host, $user, $pwd, $db);

if(mysqli_connect_errno($con)) {
    die("Failed to connect to MySQL: " . mysqli_connect_error());
} 


$sql = "SELECT Grad, Predmet FROM lista";
$result = mysqli_query($con, $sql);

$rows = array();

while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

        $rows[] = $row; 
    }

mysqli_close($con);

$rows = (object) array('lista' => $rows);
echo json_encode($rows);

脚本正在返回:

{"lista":[{"Grad":"Beograd","Predmet":"matematika"},{"Grad":"Novi_Sad","Predmet":"matematika"},{"Grad":"Beograd","Predmet":"matematika"},{"Grad":"Novi_Sad","Predmet":"matematika"},{"Grad":"Beograd","Predmet":"informatika"},{"Grad":"Beograd","Predmet":"informatika"}]}
4

2 回答 2

1

试试这个功能http://php.net/manual/en/function.array-unique.php

array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )

来自 php.net 文档的示例:

<?php
    $input = array("a" => "green", "red", "b" => "green", "blue", "red");
    $result = array_unique($input);
    print_r($result);
?>
于 2013-07-30T08:25:51.127 回答
0

Replace this:

$rows = (object) array('lista' => $rows);
echo json_encode($rows);

With this:

$lista = array_map('unserialize', array_unique(array_map('serialize', $rows)));
echo json_encode((object) array('lista' => $lista));
于 2013-07-30T08:53:21.070 回答