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

报告相同问题?

悬赏问题

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