Search code examples
phpsortingmaxslice

Keep only the three highest values in array of array in php


I have an array of 83 arrays (an array that I have a chunk in 83). I'm trying to keep only the three highest values of each array. All the numbers in each array are included between -1 and 1. There is necessarily a 1 in each array that I don't want to count in my three highest values.

        Array
    (
        [0] => Array
            (
                [1] => 0.5278533158407
                [2] => 0.4080014506744
                [3] => 0.5086879008467
                [5] => 0.3950042642736
                [6] => 1
        [1] => Array
            (
                [1] => 1
                [2] => 0.52873390443395
                [3] => 0.52518076782133
                [4] => 0.52983621494599
                [5] => 0.54392829322042
                [6] => 0.53636363636364

Etc...

I'm trying the below code but it doesn't work.

for ($i = 0; $i < sizeof($list_chunk); $i++) {
        arsort($list_chunk[$i]);
        }
        
for ($i = 0; $i < sizeof($list_chunk); $i++) {
        array_slice($list_chunk[$i],1,3,true);
        }
        
   
print("<pre>");
print_r($list_chunk);
print("</pre>");

   

Someone could help me? Thanks a lot


Solution

  • This solution uses a foreach loop with a reference to the subarray. The subarray is sorted in descending order of size. The first to third elements are extracted. If the first element is 1, then 3 elements are extracted from the 2 element onwards.

    foreach($array as &$arr){
      rsort($arr);
      $start = $arr[0] == 1 ? 1 : 0;
      $arr = array_slice($arr,$start,3);
    }
    

    Result:

    array (
      0 => 
      array (
        0 => 0.5278533158407,
        1 => 0.5086879008467,
        2 => 0.4080014506744,
      ),
      1 => 
      array (
        0 => 0.54392829322042,
        1 => 0.53636363636364,
        2 => 0.52983621494599,
      ),
    )
    

    Full sample to try: https://3v4l.org/pUhic