views:

20

answers:

2

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')

);

A: 
$summedUp = 3*$data[1]['attack'] + 4*$data[3]['attack'] + 2*$data[2]['attack'];
Ishtar
I know how to do it manually. The problem is that the limit will be different each time and I want to do it inside a loop.
Chris Ford
A: 

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;
}
zerkms
Thank you for your answer, it is really helpful, but I forgot to state that the limit will be total amount which is in the array, not the attack amount. That is what I want, and sorry for taking your time.
Chris Ford
@Chris Ford: I cannot get what you meant. Correct your initial question according your comment.
zerkms
The first solution you have written was not what I want, but that one did the trick. Thank you for your answer.
Chris Ford