本文介紹了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'));
這篇關于php數組中重復元素的數量的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯(lián)網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯(lián)系我們刪除處理,感謝您的支持!