Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

php - 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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...