[英]PHP array - count unique IDs
I have a PHP array that looks like this 我有一个看起来像这样的PHP数组
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 我正在尝试获取唯一ID的总数,因此在上面的示例中,我希望获得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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.