duandianwen1723 2017-09-10 05:49
浏览 21
已采纳

如何在php中的一列中仅在一行和相同日期添加一天的销售?

i have a array result like the below. it show every payment on each day but i want to add the all the payment in of a day in only one row and the date in one col how can i do that ? thanks

Array ( [cols] => 2017-09-10 [rows] => 1311.45 ) [1] => Array ( [cols] => 2017-09-10 [rows] => 1311.45 ) [2] => Array ( [cols] => 2017-09-10 [rows] => 175000.00 )

my code look like this

 foreach($Todaysales as $d)

 {

     $data[] = ['cols' => date("Y-m-d", strtotime($d['sale_time'])),'rows' => $d['payment_amount']];

 }

My desired output is

[[cols]=> 2017-09-10 [rows]=> sum(2017-09-10's sales)]

edited code

 $data=Array
(
    [2017-09-10] => 178934.35
    [2017-09-09] => 700000
    [2017-09-07] => 194432.25
    [2017-09-06] => 183252.9
    [2017-09-03] => 1311.45
    [2017-09-02] => 1186.55
    [2017-08-30] => 204660.3
    [2017-08-29] => 290486.45
    [2017-08-28] => 2400
    [2017-08-27] => 600.00
    [2017-08-26] => 840.00
    [2017-08-16] => 600.00
)

to this format after json encoding

[{"cols":"2017-09-02 ","rows":"1186.55"},{"cols":"2017-09-03","rows":"1311.45"}
  • 写回答

3条回答 默认 最新

  • dpmir1988 2017-09-10 06:14
    关注

    Try below code you will get date as key and sum of sales amount as value

    foreach($Todaysales as $d)
    
     {
    
         if(isset($data[$d['sale_time']]))
             $data[$d['sale_time']] += $d['payment_amount'];
         else
             $data[$d['sale_time']] = $d['payment_amount'];
    
     }
     print_r($data);
    

    DEMO

    EDIT If you want same output as you specified. You can try following

    $data = array();
    foreach($Todaysales as $d)
    {
         $match_key =false;
         $match_key = array_search($d['sale_time'],array_column($data, "cols"));
    
         if($match_key > 0 || $match_key === 0)
            $data[$match_key]["rows"] = $data[$match_key]["rows"] + $d['payment_amount'];
         else
             $data[] = array("cols"=>$d['sale_time'],"rows"=>$d['payment_amount']);
    
    }
    print_r($data);
    

    DEMO

    EDIT as per your comment you need it for google chart try below answer:

    foreach($Todaysales as $d)
    
     {
    
         if(isset($data[$d['sale_time']]))
             $data[$d['sale_time']] += $d['payment_amount'];
         else
             $data[$d['sale_time']] = $d['payment_amount'];
    
     }
    
     $new_data["cols"] ="'".implode("','",array_keys($data))."'";
     $new_data["rows"] =implode(",",array_values($data));
     print_r($new_data);
    

    DEMO

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

报告相同问题?

悬赏问题

  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧