如何在PHP中删除重复的数组对象?

时间:2017-11-06 09:40:22

标签: php

我在下面有这个代码,它将获得数组对象。

// fetch all circuits
$circuits = $Tools->fetch_all_circuits();

// check locations
if($circuits!==false) {
    // all locations
    $all_locations = array ();
    // loop
    foreach ($circuits as $circuit) {
        // format points
        $locationA = $Tools->reformat_circuit_location ($circuit->device1, $circuit->location1);
        $locationB = $Tools->reformat_circuit_location ($circuit->device2, $circuit->location2);

        if($locationA['location']!="" && $locationB['location']!="") {
            $locA = $Tools->fetch_object ("locations", "id", $locationA['location']);
            $locB = $Tools->fetch_object ("locations", "id", $locationB['location']);
            // save to all_locations array
            if ($locA!==false && $locB!==false) {
                $all_locations[] = $locA;
                $all_locations[] = $locB;
            }
        }
    }
}

var_dump ($all_locations);

如何从此数组中获取唯一对象?

我var_dump($ all_locations),我有这个数组输出(我删除了一些对象,以减少输出)。

array(28) { [0]=> object(stdClass)#51 (6) { ["id"]=> string(3) "950"
["name"]=> string(4) "5829" ["description"]=> string(4) "Null"
["address"]=> string(4) "Null" ["lat"]=> string(7) "21.5336"
["long"]=> string(7) "39.2178" } [1]=> object(stdClass)#52 (6) {
["id"]=> string(3) "987" ["name"]=> string(4) "5765" ["description"]=>
string(4) "Null" ["address"]=> string(4) "Null" ["lat"]=> string(7)
"21.5439" ["long"]=> string(7) "39.2243" } [2]=> object(stdClass)#54
(6) { ["id"]=> string(4) "1016" ["name"]=> string(4) "2228"
["description"]=> string(4) "Null" ["address"]=> string(4) "Null"
["lat"]=> string(7) "21.5447" ["long"]=> string(7) "39.2301" } [27]=>
object(stdClass)#84 (6) { ["id"]=> string(4) "2536" ["name"]=>
string(4) "2389" ["description"]=> string(4) "Null" ["address"]=>
string(4) "Null" ["lat"]=> string(6) "21.495" ["long"]=> string(6)
"39.966" } }

1 个答案:

答案 0 :(得分:0)

array_unique()会帮助您。 http://php.net/manual/en/function.array-unique.php

array_unique()首先对作为字符串处理的值进行排序,然后保留每个值遇到的第一个键,并忽略所有后续键。这并不意味着将保留未排序数组中第一个相关值的键。