开发者

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

开发者 https://www.devze.com 2023-01-22 17:19 出处:网络
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

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开发者_Go百科' => '4', 'attack' => '20', 'defence' => '10', 'total' => '4')

);


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;
}


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

精彩评论

暂无评论...
验证码 换一张
取 消