PHP Array_unique

88 Views Asked by At

Is it possible to remove sub arrays, if the array item at position 0 of that sub array matches subsequent items?

For example;

Array ( [0] => Array ( [0] => 1234 [1] => XX000 ) 
        [1] => Array ( [0] => 1234 [1] => XX001 ) 
        [2] => Array ( [0] => 1234 [1] => XX002 ) 
      )

Would be adjusted to output;

Array ( [0] => Array ( [0] => 1234 [1] => XX000 ) )
3

There are 3 best solutions below

3
user1235285 On BEST ANSWER

Always the way, I've found out the solution after posting this ($query being the multi-dimensional array);

$newArr = array();

foreach ($query as $val) {
    $newArr[$val[0]] = $val;    
}

$query = array_values($newArr);
0
Wakeel On

function my_array_filter($arr){
    $exist = [];

    return array_filter($arr, function($element){
         if( ! array_key_exist($element[0], $exist)){
            $exist[$element[0]] = true;
            return true;
         }
         return false;
     });
}
0
Erwin Moller On

Maybe it is possible with some arcane usage of array functions and callback, but I prefer keeping things simple whenever possible, so I understand my own solutions years later.

So why not program it?

$ORG = [ [ 1234, 'XX000' ],  
         [ 1234, 'XX001' ],  
         [ 1234, 'XX002' ], 
         [19987, 'XX000'] ];

$NEW = [];
$USEDKEYS = [];

foreach ($ORG as $one){
    if (in_array($one[0], $USEDKEYS)) {
        // skip.   
    } else {
        $NEW[] = $one;
        $USEDKEYS[] = $one[0];
    }
}
unset ($USEDKEYS, $ORG);
var_dump ($NEW);