从对象php中删除重复的项目

时间:2018-03-11 12:59:59

标签: php

{"id":34,"first_name":"xus"}
{"id":34,"first_name":"xus"}
{"id":4,"first_name":"ABC"}
{"id":4,"first_name":"ABC"}

$newlist = [];
$values = [];
foreach ($appointment_list as $key => $value) {
    # code...
    $values[] = $value['users'];
    foreach($values as $val){

            $newlist[$val->id]=$values;
    }
    unset($newlist[$key][$values]);
}

我想从对象中删除重复值显示不同的基于id的值并且想要计算每个id的重复存在

预期

id 34 has 2 duplicate

它应该返回一个对象

{"id":34,"first_name":"xus", "count":2} 

类似的东西

2 个答案:

答案 0 :(得分:1)

您可以使用array_reduce

$arr = array(
    array("id" => 34,"first_name" => "xus"),
    array("id" => 34,"first_name" => "xus"),
    array("id" => 4,"first_name" => "ABC"),
    array("id" => 4,"first_name" => "ABC"),
);

$result = array_reduce($arr, function($c, $v){
    if ( !isset( $c[$v["id"]] ) ) {
        $c[$v["id"]] = $v;
        $c[$v["id"]]["count"] = 1;
    } else {
        $c[$v["id"]]["count"]++;
    }
    return $c;
}, array());

$result = array_values( $result );

echo "<pre>";
print_r( $result );
echo "</pre>";

这将导致:

Array
(
    [0] => Array
        (
            [id] => 34
            [first_name] => xus
            [count] => 2
        )

    [1] => Array
        (
            [id] => 4
            [first_name] => ABC
            [count] => 2
        )

)

答案 1 :(得分:0)

最简单的方法是创建一个空数组并使用&#34; id&#34;映射您的对象。作为关键。

这是工作代码段

<?php
$objectsRaw = [];
$objectsRaw[] = '{"id":34,"first_name":"xus"}';
$objectsRaw[] = '{"id":34,"first_name":"xus"}';
$objectsRaw[] = '{"id":4,"first_name":"ABC"}';
$objectsRaw[] = '{"id":4,"first_name":"ABC"}';

# decode the json objects into PHP arrays
$objects = array_map(
    function($objectJson) {
        $object = json_decode($objectJson, true);
        return $object;
    },
    $objectsRaw
);

# map the objects
$result = [];
foreach($objects as $object) {
    if (array_key_exists($object['id'], $result) === false) {
        $object['count'] = 1;
        $result[$object['id']] = $object;
        continue;
    }
    $result[$object['id']]['count']++;
}

# encode result
$resultRaw = array_map('json_encode', $result);
# would look like
# Array
# (
#     [34] => {"id":34,"first_name":"xus","count":2}
#     [4] => {"id":4,"first_name":"ABC","count":2}
# )

# reset array keys (if you need this)
$resultRaw = array_values($resultRaw);
# would look like
# Array
# (
#     [0] => {"id":34,"first_name":"xus","count":2}
#     [1] => {"id":4,"first_name":"ABC","count":2}
# )