dsa88885555 2017-10-10 07:00
浏览 65
已采纳

php计算每10个数组元素的总数

Array ( 
    [0] => Array ( 
        [amount_paid] => 2050.00 
    )
    [1] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [2] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [3] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [4] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [5] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [6] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [7] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [8] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [9] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [10] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [11] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [12] => Array ( 
        [amount_paid] => 2050.00 
    ) 
    [13] => Array ( 
        [amount_paid] => 2050.00 
    ) 

) 

I have this example of array in php. I want to sum up every 10 paid amount.

Example is sum index 0-9 , 10 - 19 and so on

What I tried is only for first 10 and I cant think how to handle for every 10 with dynamic number

for ($i = 0; $i < count($json); $i++) {
    if ($i < 10) {
        $subtotalamount += floatval($json[$i]['amount_paid']);
    }
}
  • 写回答

5条回答 默认 最新

  • douyu9159 2017-10-10 07:12
    关注

    Short solution with range, array_slice and array_column functions:

    // $arr is your initial array
    $sub_totals = [];
    foreach(range(0, count($arr), 10) as $k){
        $sub_totals[] = array_sum(array_column(array_slice($arr, $k, 10), 'amount_paid'));
    }
    

    • range(0, count($arr), 10) - generate an array containing a range of elements. It would be as [0, 10, 20]. Those elements are boundaries for each 10-sized sequence

    • array_slice($arr, $k, 10) - each next boundary $k is used for extracting next 10-sized sequence/slice from the initial array $arr

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀