phpmultidimensional-arrayarray-unique

php filter array values and remove duplicates from multi dimensional array


Hello all im trying to find duplicate x values from this array and remove them and only leave the unique ones. For example my array is

Array
(
[0] => Array
    (
        [x] => 0.5
        [y] => 23
    )

[1] => Array
    (
        [x] => 23
        [y] => 21.75
    )

[2] => Array
    (
        [x] => 14.25
        [y] => 21.875
    )

[3] => Array
    (
        [x] => 19.375
        [y] => 21.75
    )

[4] => Array
    (
        [x] => 9.125
        [y] => 21.875
    )

[5] => Array
    (
        [x] => 23
        [y] => 19.625
    )

[6] => Array
    (
        [x] => 19.375
        [y] => 19.625
    ) 
)

So what i need to happen is loops through the entire thing and see the first x value as .5 then continue and whatever else has x as .5 remove it from the array so that at the end i have a array that looks like this

 Array
   (
[0] => Array
    (
        [x] => 0.5
        [y] => 23
    )

[1] => Array
    (
        [x] => 23
        [y] => 21.75
    )

[2] => Array
    (
        [x] => 14.25
        [y] => 21.875
    )

[3] => Array
    (
        [x] => 19.375
        [y] => 21.75
    )

[4] => Array
    (
        [x] => 9.125
        [y] => 21.875
    )
)

where all the X values are unique. I searched online and found this function to use but this doesnt seem to work:

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

Solution

  • Just loop through and find unique values as you go:

    $taken = array();
    
    foreach($items as $key => $item) {
        if(!in_array($item['x'], $taken)) {
            $taken[] = $item['x'];
        } else {
            unset($items[$key]);
        }
    }
    

    Each the first time the x value is used, we save it - and subsequent usages are unset from the array.