douzi7219 2017-10-19 11:44
浏览 38

使用php以最佳方式计算多数组的键

I have the following array (decoded from json in php ):

array [
    array("num"=>1,"test"=123, "key"=4),
    array("num"=>2,"test"=123, "key"=3),
    array("num"=>3,"test"=124, "key"=2),
    array("num"=>4,"test"=125, "key"=7),
    array("num"=>5,"test"=125, "key"=8),
    array("num"=>6,"test"=123, "key"=5)
]

I would like to count the "test" key and return all the related arrays with the same key: 123 has the most appearance in the array

so I would like to get the following result (list of the arrays that appears most):

array[
   array("num1"=1 , "test"=123","key" = 4)    
   array("num1"=2 , "test"=123", "key" = 3)    
   array("num1"=6 , "test"=123" ,"key" = 5)    

]

and then(can be done of course in the same loop if possible) from that list, I want to take this with the highest key:

   array("num1"=6 , "test"=123" ,"key" = 5)    

How can I do that in the best way in php? thanks a lot

  • 写回答

1条回答 默认 最新

  • douchong4730 2017-10-19 11:57
    关注

    Something like this might work, All the functions have an excellent explanation on PHP.net

    <?php
    $keyCounts = array_count_values( array_column( $arr, 'test' ));
    $maxs = array_keys($arr, max($keyCounts ));
    $filtered = array_filter($arr , function($row) { 
        return $row['test'] === $maxs; 
    });
    $filteredMax = max(array_column( $filtered , 'key' );
    $final  = array_filter($filtered  , function($row) { 
        return $row['key'] === $filteredMax; 
    });
    

    EDIT: It is unlikely that this code will work, but it should point you in the right directions and the right functions to use to find the right solution yourself.

    评论

报告相同问题?