0

I have an 2D array, it is simple as this:

[0] => Array
    (
        [0] => 6
        [1] => 6
        [2] => 6
    )

[1] => Array
    (
        [0] => 6
        [1] => 6
        [2] => 11
    )

[2] => Array
    (
        [0] => 6
        [1] => 6
        [2] => 6
    )

Of course, they are inside of another array. What I want is to remove index[2] because it has same values as index[0]. I searched here and on google but couldn't find how to solve issue exactly like this one. Thank you in advance.

mihajlo
  • 108
  • 2
  • 4
  • 15
  • 1
    Have a look at http://stackoverflow.com/questions/369602/how-to-delete-an-element-from-an-array-in-php (unsetting an element in a php array) – fvu May 08 '13 at 23:36
  • 2
    Did you search the [PHP docs](http://php.net/manual/en/function.array-unique.php)? – nice ass May 08 '13 at 23:36
  • Yes, but that will remove only value, I want to remove complete index. – mihajlo May 08 '13 at 23:39
  • @fvu In your case, first I must find duplicates and then unset them. I think there is a function that does both at the same time and I have used it but can't remember right now.. – mihajlo May 08 '13 at 23:44

4 Answers4

3

Look at array_unique with SORT_REGULAR flag.

array_unique($your_array, SORT_REGULAR);
clime
  • 8,695
  • 10
  • 61
  • 82
  • 1
    @zavg: you should use SORT_REGULAR, otherwise it performs conversion of inner arrays always producing 'Array'. – clime May 08 '13 at 23:50
  • @ItayMoav-Malimovka I think that NOTE might come from times before sort_flags added. I really don't see a reason why it should not work now if you can do array(1,2,3) === array(1,2,3). – clime May 08 '13 at 23:58
  • @clime Ok, agree, it works cause I tested it on 2 elements array. – zavg May 09 '13 at 00:03
  • will try it right away - it works..I have misunderstood the function. Thank you @clime – mihajlo May 09 '13 at 00:08
0

don't crare too much on performance.

$dict = array();
foreach($your_data as $one_index){
  $dict[join('',$one_index)]=$one_index;
}

$res=array();
foreach($dict as $one_index){
   $res[] = $one_index;
}

var_dump($res);
Itay Moav -Malimovka
  • 52,579
  • 61
  • 190
  • 278
0

I can suggest having a hash sum calculated for every sub-array in case you have many sub-arrays with many values. Then store that hash into a new array or as an element of the sub-array. Then itterate through comparing hashes and unset($foundArray); for matches.

Xeos
  • 5,975
  • 11
  • 50
  • 79
  • Array has no more than 25 'main' indexes, and I know there is a simple way (I did it before) but just can't remember. – mihajlo May 08 '13 at 23:49
0

try this

function array_unique_recusive($arr){
foreach($arr as $key=>$value)
if(gettype($value)=='array')
    $arr[$key]=array_unique_recusive($value);
return array_unique($arr,SORT_REGULAR);
}

as mentioned here http://php.net/manual/en/function.array-unique.php

RST
  • 3,899
  • 2
  • 20
  • 33