简体   繁体   中英

PHP array - count unique IDs

I have a PHP array that looks like this

Array
(
    [0] => Array
        (
            [events] => Array
                (
                    [0] => Array
                        (
                            [label] => apple
                            [id] => 3
                        )
                        [1] => Array
                        (
                            [label] => onion
                            [id] => 3
                        )
                        [2] => Array
                        (
                            [label] => pear
                            [id] => 2
                        )
                        [3] => Array
                        (
                            [label] => orange
                            [id] => 1
                        )
                        [4] => Array
                        (
                            [label] => grape
                            [id] => 41
                        )
                )
        )
)

I am trying to get a total count of unique IDs, so in the example above I would want to get a count of 4

Do I need to loop through the array or is there a function that can do it more efficiently? Currently it is a small data set but it could grow fairly large.

您可以使用array_column获取所有ID,并使用array_unique删除重复项,然后对其进行计数。

count(array_unique(array_column($array[0]['events'][0], 'id')))

One way or another you'll have to loop through it. I think most efficiently would be

function getUnique($arr){
 $val = array();
  foreach($arr[0]["events"] as $v){
   $val[$v["id"]] = true;
  }
 return count($val);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM