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 ) )
0

3 Answers 3

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;
     });
}
Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

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);

3 Comments

You can accept your own answer, which will help others who read this in the future
Very similar to this method would be $query = array_values(array_column($query, null, 0));.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.