PHP - Count duplicate values within two dimensional array, then display only unique values with the count

后端 未结 2 1420
难免孤独
难免孤独 2020-12-12 01:14

I\'ve been working on this for a couple days now... and still haven\'t been able to achieve my desired results. Any help would on this would be greatly appreciated... thank

2条回答
  •  清歌不尽
    2020-12-12 01:44

    If you are using PHP >= 5.5, you can use array_column(), in conjunction with array_count_values():

    $colors = array_count_values(array_column($log, 0));
    $materials = array_count_values(array_column($log, 1));
    

    See demo


    Or, if you're not using PHP >= 5.5, this will work in PHP 4, 5:

    $colors = $materials = array();
    foreach ($log as $a){
        $colors[] = $a[0];
        $materials[] = $a[1];
    }
    
    $colors = array_count_values($colors);
    $materials = array_count_values($materials);
    

    See demo 2


    Click here for sample use case that will work with either method.

提交回复
热议问题