使用范围val组织数组

I’m working on an array of numeric values.

I have a array of numeric values as the following in PHP

array('85kg' => '1', '87kg' => '3', '88kg' => '1', '90kg' => '3', '98kg' => '1')

And I’m trying to convert it into range for e.g in above case it would be:

array('85kg-88kg' => '5', '89kg-92kg' => '3', '97kg-100kg' => '1')

Range 3kg any key.. I don’t have any idea how to convert it into range.

You could get the first key, and last key as integer using cast ((int)). Then, you could create a loop from the first key, until you reach the last key. Inside it, you could loop over the initial array and check if the key is inside the range. If so, you could append the current value to the final array:

$arr = array('85kg' => '1', '87kg' => '3', '88kg' => '1', '90kg' => '3', '98kg' => '1');
$first_key = (int)key($arr); // 85
end($arr); // move to the last element to get the last key,
$last_key = (int)key($arr); // 98
$it = $first_key;
while ($it <= $last_key) { // from 85 - 98
    foreach ($arr as $key => $val) {
        $intk = (int)$key ; // 85, 87, 88, 90, 98
        if ($intk >= $it && $intk <= $it +3) { 
            $arrk = $it.'kg-'.($it+3).'kg'; // create key
            if (!isset($out[$arrk])) $out[$arrk] = 0; // create key in array
            $out[$arrk] += $val ; // append value
        }
    }
    $it += 4; // += 3 + 1 (new weight)
}
print_r($out);

Will outputs:

Array
(
    [85kg-88kg] => 5
    [89kg-92kg] => 3
    [97kg-100kg] => 1
)