简体   繁体   中英

How do I get sum of value based on same key until some point in an array?

I have an array as following. I order that array by the value of the key "attack". Everything is ok until then, but I want to get for example only 9 of that total attack values are summed up: I want to sum up 3 of key1 (3 * 45), 4 of key3 (4 * 35) and 2 of key2 (2* 25) are automatically summed up. I would be greatly appreciated if somebody help.

Here is the array:

$data = array(
'1' => array('id' => '1', 'attack' => '45', 'defence' => '15', 'total' => '3'),
'2' => array('id' => '2', 'attack' => '25', 'defence' => '15', 'total' => '6'),
'3' => array('id' => '3', 'attack' => '35', 'defence' => '15', 'total' => '4'),
'4' => array('id' => '4', 'attack' => '20', 'defence' => '10', 'total' => '4')

);

$summedUp = 3*$data[1]['attack'] + 4*$data[3]['attack'] + 2*$data[2]['attack'];

Here is my sample implementation:

$data = array(
'1' => array('id' => '1', 'attack' => '45', 'defence' => '15', 'total' => '3'),
'2' => array('id' => '2', 'attack' => '25', 'defence' => '15', 'total' => '6'),
'3' => array('id' => '3', 'attack' => '35', 'defence' => '15', 'total' => '4'),
'4' => array('id' => '4', 'attack' => '20', 'defence' => '10', 'total' => '4')
);

usort($data, 'sort_by_attack');

$attacks_amount = 9;
$sum = 0;

$row = current($data);

while ($attacks_amount > 0) {
        $attacks_amount -= $row['total'];
        $take = $row['total'];

        if ($attacks_amount < 0) {
                $take += $attacks_amount;
        }

        $sum += $take * $row['attack'];

        $row = next($data);
        if (!$row) break;
}

var_dump($sum);

function sort_by_attack($a, $b)
{
        return $a['attack'] > $b['attack'] ? -1 : 1;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM