从PHP数组中删除重复项

时间:2013-07-30 08:23:36

标签: php

我的PHP脚本正在返回一些数组,我想删除该数组中的重复项。你能告诉我怎么样吗?我不想从PHP中删除重复项,只需从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"}]}

2 个答案:

答案 0 :(得分: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);
?>

答案 1 :(得分:0)

替换它:

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

有了这个:

$lista = array_map('unserialize', array_unique(array_map('serialize', $rows)));
echo json_encode((object) array('lista' => $lista));