计算一个值出现在多维数组中的次数
问题描述:
我有一个简单的多维数组,如下所示。我试图计算阵列中每个值存在多少次(即关节炎=> 3)。我已经尝试了所有不同的PHP函数,但它总是返回一个数字而不是一个key =>值对。我也看过类似的问题,但没有什么真正符合我的数组的简单性。计算一个值出现在多维数组中的次数
array(3) {
[0]=>
array(1) {
[0]=>
string(0) "Arthritis"
}
[1]=>
array(4) {
[0]=>
string(7) "Thyroid"
[1]=>
string(10) " Arthritis"
[2]=>
string(11) " Autoimmune"
[3]=>
string(7) " Cancer"
}
[2]=>
array(6) {
[0]=>
string(7) "Anxiety"
[1]=>
string(10) " Arthritis"
[2]=>
string(11) " Autoimmune"
[3]=>
string(15) " Bone and Joint"
[4]=>
string(7) " Cancer"
[5]=>
string(8) " Candida"
}
}
<?php
print_r(count($items, COUNT_RECURSIVE));
?>
答
一种方法是把它压扁成使用在子阵array_merge()
一个维度,然后使用array_count_values()
算值:
$count = array_count_values(call_user_func_array('array_merge', $items));
答
听起来像是你需要一个定制的循环:
$counts = array();
foreach ($items as $item) {
foreach ($item as $disease) { // $disease here is the string like "Arthritis"
if (isset($counts[$disease])) // $disease then become the key for the resulting array
$counts[$disease]++;
else
$counts[$disease] = 1;
}
}
print_r($counts);
谢谢,不知道它可以在一行中解决,非常感谢 – DEM