Array Unique, based only on the first value?

My array:

$arr = [['abc', 'a'],['xyz', 'f'],['abc', 'x']];

I need to remove any duplicate first values, e.g. there are two abc values ​​above, array_unique will not work as the second value is different:

 $arr = array_unique($arr, SORT_REGULAR);

Is there a way to get only unique values ​​based on the first value. I cannot change the structure above.

Required Result:

$arr = [['abc', 'a'],['xyz', 'f']];
+4
source share
1 answer

array_combine () and array_column () may help, But this will change the order of the nested arrays and will only contain the last value for duplicates.

$arr = [['abc', 'a'],['xyz', 'f'],['abc', 'x']];
$temp = array_combine(array_column($arr, 0), $arr);

array_columnnot available for older versions. (Available in (PHP 5> = 5.5.0, PHP 7) )

Output

array(2) {
  ["abc"]=>
  array(2) {
    [0]=>
    string(3) "abc"
    [1]=>
    string(1) "x"
  }
  ["xyz"]=>
  array(2) {
    [0]=>
    string(3) "xyz"
    [1]=>
    string(1) "f"
  }
}

array_column - 0.

array_combine , array_column.

, ( 0) . , () .

+5

Source: https://habr.com/ru/post/1651524/


All Articles