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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度