1

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 ) )
Erwin Moller
  • 2,375
  • 14
  • 22
user1235285
  • 87
  • 2
  • 17

3 Answers3

2

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;
     });
}
Wakeel
  • 4,272
  • 2
  • 13
  • 14
2

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);
Erwin Moller
  • 2,375
  • 14
  • 22
1

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);
user1235285
  • 87
  • 2
  • 17
  • You can accept your own answer, which will help others who read this in the future – Mawg says reinstate Monica Nov 13 '20 at 08:32
  • Very similar to this method would be `$query = array_values(array_column($query, null, 0));`. – Nigel Ren Nov 13 '20 at 08:42
  • That works, but you must be aware that your keys are now coming from the inner array-value[0]. So they might be 2, 54, 4, 99 etc. (as opposed to 0,1,2,3,etc) That might not be a problem in your situation, but it is something to consider. – Erwin Moller Nov 13 '20 at 08:57