0

How can I remove duplicate arrays? it's different from array unique because that is removing duplicate values inside array..

i get an array list like this

1. array('item' => 6, 'quantity' => 1, 'price' => 120)
2. array('item' => 6, 'quantity' => 1, 'price' => 120)
3. array('item' => 6, 'quantity' => 1, 'price' => 120)
4. array('item' => 22, 'quantity' => 8, 'price' => 30)
5. array('item' => 22, 'quantity' => 8, 'price' => 30)

how do i make like this while keeping the values?

3. array('item' => 6, 'quantity' => 1, 'price' => 120)
4. array('item' => 22, 'quantity' => 8, 'price' => 30)

code

$get = file_get_contents('URL');    
$json = json_decode($get, true);    
$results = print_r($json);    
file_put_contents('file.json', print_r($json, true), FILE_APPEND);
fcbrmadrid
  • 99
  • 4

2 Answers2

1

This should work for you:

$unique = array_map("unserialize", array_unique(array_map("serialize", $array)));

So as a example:

<?php

    $array = array(
                array('item' => 6, 'quantity' => 1, 'price' => 120),
                array('item' => 6, 'quantity' => 1, 'price' => 120),
                array('item' => 6, 'quantity' => 1, 'price' => 120),
                array('item' => 22, 'quantity' => 8, 'price' => 30),
                array('item' => 22, 'quantity' => 8, 'price' => 30)
            );

    $unique = array_map("unserialize", array_unique(array_map("serialize", $array)));

    echo "<pre>";
    print_r($unique);

?>

Output:

Array
(
    [0] => Array
        (
            [item] => 6
            [quantity] => 1
            [price] => 120
        )

    [3] => Array
        (
            [item] => 22
            [quantity] => 8
            [price] => 30
        )

)
Rizier123
  • 58,877
  • 16
  • 101
  • 156
0

Also you can try this way:

if(serialize($a1) == serialize($a2))

You can serializ the arrays and then compare.

Pupil
  • 23,834
  • 6
  • 44
  • 66