简体   繁体   中英

Sum up array values by keys

I need to sum up some values from subarrays in an array.

I have this array

Array
(
    [smecid_2] => Array
        (
            [0] => 1
            [1] => SMEC 55.6
            [2] => 960
            [3] => 864
            [4] => 960
            [5] => 864
        )

    [smecid_6] => Array
        (
            [0] => 3
            [1] => SMEC 55.6 ATEX EX
            [2] => 1290
            [3] => 1161
            [4] => 3870
            [5] => 3483
        )

)

What I want to do is sum up all fields from key [4] of each subarray and be able to echo the total in $total;

In this example $total; would be 4830 (960+3870).

Also, the array could hold more subarrays then these 2, when a user submits more products to order.

<?php
$array = array
(
    'smecid_2' => array
        (
            0 => 1,
            1 => 'SMEC 55.6',
            2 => 960,
            3 => 864,
            4 => 960,
            5 => 864,
        ),

    'smecid_6' => array
        (
            0 => 3,
            1 => 'SMEC 55.6 ATEX EX',
            2 => 1290,
            3 => 1161,
            4 => 3870,
            5 => 3483,
        )

);

$sum = 0;
foreach ($array as $subarray)
{
    $sum += $subarray[4];
}
echo $sum;

See it in action

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