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

951

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

630

Answer

Solution:

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);

People are also looking for solutions to the problem: php - Laravel- Authorize.net not working in production mode

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.