我有一系列像这样的车.
Array ( [2] => Car Object ( [userId] => 3 [value] => 0 ) [58] => Car Object ( [userId] => 2 [value] => 0 ) [64] => Car Object ( [userId] => 2 [value] => 0 ) )
我遍历一组用户,并希望知道每个userId出现在cars数组中的次数.数组键是动态数字.每次循环通过用户阵列时,是否需要遍历cars数组?好像很多循环,我怀疑有更好的解决方案:)
提前致谢
更新:我实际上只是想出了一个似乎有用的解决方案.可能不漂亮.评论表示赞赏
$countArray = array(); foreach($cars as $car) { if(!$countArray[$car->userId()]) $countArray[$car->userId()] == 0; $countArray[$car->userId()]++; }
print_r($ countArray)给了我
Array ( [94] => 33 [84] => 15 [88] => 53 [80] => 69 [83] => 14 [93] => 3 [76] => 69 [86] => 51 [82] => 77 [87] => 20 [112] => 12 [115] => 16 [114] => 10 [113] => 2 [77] => 1 )
这似乎是正确的
array_count_values( array_map(function($v) { return $v->userId; }, $array) );
结果
Array ( [3] => 1 [2] => 2 )