Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique value in multidimensional array

I have done a lot of looking around on the overflow, and on google, but none of the results works for my specific case.

I have a placeholder array called $holder, values as follows:

    Array (      [0] => Array (          [id] => 1          [pid] => 121          [uuid] => 1           )     [1] => Array (          [id] => 2          [pid] => 13         [uuid] => 1         )     [2] => Array (          [id] => 5          [pid] => 121          [uuid] => 1         )     )  

I am trying to pull out distinct/unique values from this multidimensional array. The end result I would like is either a variable containing (13,121), or (preferrably) an array as follows: Array( [0] => 13 [1] => 121 )

Again I've tried serializing and such, but don't quite understand how that works when operating with a single key in each array.

I tried to be as clear as possible. I hope it makes sense...

like image 396
MaurerPower Avatar asked May 02 '12 06:05

MaurerPower


People also ask

What is a unique value in an array?

You can find the distinct values in an array using the Distinct function. The Distinct function takes the array as an input parameter and returns another array that consists only of the unique, or non-duplicate, elements. The following example shows how to find the distinct values in an array.

How can I get unique values from two arrays in PHP?

You can use the PHP array_unique() function and PHP array_merge() function together to merge two arrays into one array without duplicate values in PHP.

How do you represent a multidimensional array?

You can create a multidimensional array by creating a 2-D matrix first, and then extending it. For example, first define a 3-by-3 matrix as the first page in a 3-D array. Now add a second page. To do this, assign another 3-by-3 matrix to the index value 2 in the third dimension.


1 Answers

Seems pretty simple: extract all pid values into their own array, run it through array_unique:

$uniquePids = array_unique(array_map(function ($i) { return $i['pid']; }, $holder)); 

The same thing in longhand:

$pids = array(); foreach ($holder as $h) {     $pids[] = $h['pid']; } $uniquePids = array_unique($pids); 
like image 57
deceze Avatar answered Sep 20 '22 22:09

deceze