問題描述
我們?nèi)绾握业?code>多維數(shù)組中重復(fù)元素的數(shù)量?
Hi,
How can we find the count of duplicate elements in a multidimensional array
?
我有一個(gè)這樣的數(shù)組
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
)
)
如何求每個(gè)元素的個(gè)數(shù)?
How to find the count of each elements ?
即,id為192
、202
等的條目數(shù)
i.e, count of entries with id 192
,202
etc
推薦答案
你可以采用這個(gè)技巧;將數(shù)組的每一項(xiàng)(它本身就是一個(gè)數(shù)組)映射到其各自的 ['lid']
成員,然后使用 array_count_value()
為您進(jìn)行計(jì)數(shù).
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'));
這篇關(guān)于php數(shù)組中重復(fù)元素的數(shù)量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!