dsigg21445 2015-12-15 20:53
浏览 51
已采纳

计算对象数组中的项目

I have an array of cars like this.

Array
(
    [2] => Car Object
        (
            [userId] => 3
            [value] => 0
        )
    [58] => Car Object
        (
            [userId] => 2
            [value] => 0
        )
    [64] => Car Object
        (
            [userId] => 2
            [value] => 0
        )

)

I loop through an array of users and wish to know how many occurrences each userId is represented in the cars array. The array keys are dynamic numbers. Do I need to loop through the cars array each time I loop though the user array? Seems like a lot of looping and I suspect a better solution is available :)

Thanks in advance

Update: I actually just came up with a solution that seems to work. Might not be pretty. Comments are appreciated

$countArray = array();

foreach($cars as $car) {

    if(!$countArray[$car->userId()]) $countArray[$car->userId()] == 0;

    $countArray[$car->userId()]++;
}

print_r($countArray) gives me

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 )

which seems about right

  • 写回答

2条回答 默认 最新

  • dragon8837 2015-12-15 21:02
    关注
    array_count_values( array_map(function($v) { return $v->userId; }, $array) );
    

    result

    Array
    (
        [3] => 1
        [2] => 2
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀