phparraysmultidimensional-arrayfilteringunique

Get unique values from a column in a 2d array


I have a 2d array and need to isolate the unique columns from one column.

$array = [
    [..., 'key' => 1, ...],
    [..., 'key' => 2, ...],
    [..., 'key' => 3, ...],
    [..., 'key' => 1, ...],
    [..., 'key' => 2, ...],
    [..., 'key' => 3, ...],
    [..., 'key' => 4, ...],
    [..., 'key' => 5, ...],
    [..., 'key' => 6, ...]
];

How do I add elements to the result array only if they aren't in there already? I have the following:

$a = [];
// organize the array
foreach ($array as $k => $v) {
    foreach ($v as $key => $value) {
        if ($key == 'key') {
            $a[] = $value;
        }
    }
}
print_r($a);

Output:

Array
(
  [0] => 1
  [1] => 2
  [2] => 3
  [3] => 1
  [4] => 2
  [5] => 3
  [6] => 4
  [7] => 5
  [8] => 6
)

Instead, I want $a to consist of the unique values. (I know I can use array_unique() after looping to get the desired results, but I just want to know of any other ways.)


Solution

  • You'd have to check each value against in_array:

    $a=array();
    // organize the array by cusip
    foreach($array as $k=>$v){
        foreach($v as $key=>$value){
            if(!in_array($value, $a)){
            $a[]=$value;
            }
        }
    }