简体   繁体   中英

PHP taking an array of objects, get rid of the duplicates one

I have this array:-

$arr
: array = 
  0: object(myObject) = 
    id: string = 188
    CaseNo: string = 1
    strname: string = Apple
    strContact: string = Alice
  1: object(myObject) = 
    id: string = 188
    CaseNo: string = 1
    strname: string = Apple
    strContact: string = Alice
  2: object(myObject) = 
    id: string = 189
    CaseNo: string = 3
    strname: string = Amazon
    strContact: string = Jules

As you can see, the two first objects in the array are repeated, how can get the same array without the repeated object, meaning:

$arr
: array = 
  0: object(myObject) = 
    id: string = 188
    CaseNo: string = 1
    strname: string = Apple
    strContact: string = Alice
  1: object(myObject) = 
    id: string = 189
    CaseNo: string = 3
    strname: string = Amazon
    strContact: string = Jules 

Please notice that this is an example array. The number of items in the array can be more than three and the number of repeated objects inside of it can be more than two.

Thanks a lot

Use array unique function which used to remove duplication

 $a = array(
        0 => array (
            "ID" => 188,
            "CaseNo" => 1,
            "strname" => 'Apple',
            "strContact" => 'Alies'

        ),
        1 => array (
             "ID" => 188,
            "CaseNo" => 1,
            "strname" => 'Apple',
            "strContact" => 'Alies'

        ),
        2 => array (
            "ID" => 189,
            "CaseNo" => 1,
            "strname" => 'Amazon',
            "strContact" => 'Jules'

        ),
);
echo "<pre>";
$ab = array_map("unserialize", array_unique(array_map("serialize", $a)));
print_r($ab);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM