dongyan4424 2017-11-23 18:17
浏览 50
已采纳

我们如何使用php从数组中获取唯一数据的总和

I need to take sum of beds of unique date from array. I had tried with foreach but I am getting repeated data.

How can I get data like,

on 01.08.18 I have 3 bookings and sum of beds is 10

on 02.08.18 I have 3 bookings and sum of beds is 18

on 03.08.18 I have 2 bookings and sum of beds is 7

<?php
$dates = ['01.01.18', '02.01.18', '03.01.18']; //Dates are getting from daterange datepicker and preparing dates using php and stored in array. 
foreach($dates as $date) {
// fetching data from table where date is matching with "$date".
    $bookings = [
                 ['date' => '01.01.18', 'beds' => '2'],
                 ['date' => '01.01.18', 'beds' => '3'],
                 ['date' => '01.01.18', 'beds' => '5'],
                 ['date' => '02.01.18', 'beds' => '7'],
                 ['date' => '02.01.18', 'beds' => '6'],
                 ['date' => '02.01.18', 'beds' => '5'],
                 ['date' => '03.01.18', 'beds' => '2'],
                 ['date' => '03.01.18', 'beds' => '5'],
                ];

}
foreach($bookings as $booking) {
    print_r($booking['date']);
}
  • 写回答

2条回答 默认 最新

  • douxi3432 2017-11-23 19:07
    关注

    Checkout the live result here: https://3v4l.org/nHijY

    $arr = array();
    
    foreach($bookings as $booking) {
        $date = $booking['date'];
    
        if(array_key_exists($date, $arr))
            $arr[$date][] = $booking['beds'];
        else
            $arr[$date] = array($booking['beds']);
    }
    
    foreach($arr as $key => $value)
    {
        $count = count($value);
        $sum = array_sum($value);
    
        echo "on {$key} I have {$count} bookings and sum of beds is {$sum}
    ";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?