php数组中重复元素的数量
我们如何找到多维数组
中重复元素的数量?
Hi,
How can we find the count of duplicate elements in a multidimensional array
?
我有一个这样的数组
Array
(
[0] => Array
(
[lid] => 192
[lname] => sdsss
)
[1] => Array
(
[lid] => 202
[lname] => testing
)
[2] => Array
(
[lid] => 192
[lname] => sdsss
)
[3] => Array
(
[lid] => 202
[lname] => testing
)
)
如何求每个元素的个数?
How to find the count of each elements ?
即,id为192
、202
等的条目数
i.e, count of entries with id 192
,202
etc
推荐答案
你可以采用这个技巧;将数组的每一项(它本身就是一个数组)映射到其各自的 ['lid']
成员,然后使用 array_count_value()
为您进行计数.
You can adopt this trick; map each item of the array (which is an array itself) to its respective ['lid']
member and then use array_count_value()
to do the counting for you.
array_count_values(array_map(function($item) {
return $item['lid'];
}, $arr);
另外,它是单线的,因此增加了精英黑客的地位.
Plus, it's a one-liner, thus adding to elite hacker status.
从 5.5 开始,您可以将其缩短为:
Since 5.5 you can shorten it to:
array_count_values(array_column($arr, 'lid'));
相关文章