phparraysarray-sum

PHP a way to find the key after array_sum


I'm working on SMA(simple moving average) function for 5 second ( find the best average of every 5 values for one by one from an array).
I have over 1000 arrays as a result but here we only have 2 for instance.

 0 => array:5 [▼
        1608616431 => 54
        1608616432 => 71
        1608616433 => 79
        1608616434 => 75
        1608616435 => 100
      ]
      1 => array:5 [▼
        1608616432 => 71
        1608616433 => 79
        1608616434 => 75
        1608616435 => 100
        1608616436 => 99
      ]

I'd like to find the maximum of the averages from these arrays and I'm using array_sum then apply max function over them.

for the above arrays we will have avg as follows :

Avgs=[78.8,84.8]

so the maximum would be : 84.8

I need the first key of the array which the maximum comes from it, for this example would be 1608616432


Solution

  • This script will do exactly what you want

    <?php
    
    $array = [
        [
            '1608616431' => 54,
            '1608616432' => 71,
            '1608616433' => 79,
            '1608616434' => 75,
            '1608616435' => 100
        ],
        [
            '1608616432' => 71,
            '1608616433' => 79,
            '1608616434' => 75,
            '1608616435' => 100,
            '1608616436' => 99,
        ],
    ];
    
    $elementAverage = [];
    foreach ($array as $index => $element) {
        $average                                  = array_sum($element)/count($element);
        $elementArrayKeys                         = array_keys($element);
        $elementAverage[reset($elementArrayKeys)] = $average;
    }
    
    echo array_search(max($elementAverage), $elementAverage);
    

    output

    1608616432
    

    First we make $elementAverage and then get the max average
    Then just use the index and get what I want