从数组中提取“收入”总和

时间:2018-10-31 15:14:49

标签: php html arrays curl

我有一个lis数组,如何计算特定日期的收入?请在下面或此处https://3v4l.org/eUavL

查看代码

赞:

2018-10-28-29.02美元

2018-10-29-34.73美元

2018-10-30-27.22美元

==总计90.97 USD

非常感谢您的帮助!

<?php

$curl_response = '{
"options": {
    "ranking_metric": "paid_impressions",
    "time_interval": "day",
    "report_type": "time",
    "filters": {
        "pid": "2759"
    },
    "data_source": "detailed",
    "format": "json",
    "end_date": "2018-10-28 23:59",
    "columns": ["paid_impressions", "revenue"],
    "time_zone": "UTC",
    "start_date": "2018-10-26 00:00"
},
"api_url": "http://udmserve.com/udm/radalytics_api.cpx?action=report&api_key=xxxx&api_key=xxxx",
"time": 1540989662,
"rows": [{
    "paid_impressions": "18136",
    "timestamp": "2018-10-26 00:00",
    "_combined_val": "",
    "ranking_col": "49046",
    "revenue": "28.461629999999985",
    "rank": "1",
    "f0_": ""
}, {
    "paid_impressions": "14432",
    "timestamp": "2018-10-27 00:00",
    "_combined_val": "",
    "ranking_col": "49046",
    "revenue": "25.707970000000017",
    "rank": "1",
    "f0_": ""
}, {
    "paid_impressions": "16478",
    "timestamp": "2018-10-28 00:00",
    "_combined_val": "",
    "ranking_col": "49046",
    "revenue": "29.07676000000002",
    "rank": "1",
    "f0_": ""
}]
}';

 $array = json_decode($curl_response,true);
foreach($array['rows'] as $arr){
    echo explode(' ',$arr['timestamp'])[0].'-'.number_format((float)$arr['revenue'], 2, '.', '').' USD'.PHP_EOL;
}

代码也在这里:https://3v4l.org/eUavL

1 个答案:

答案 0 :(得分:2)

在迭代过程中只需保持运行总计即可。

代码:(Demo

$array = json_decode($curl_response,true);
$sum = 0;
foreach ($array['rows'] as $set) {
    $sum += $revenue = number_format((float)$set['revenue'], 2, '.', '');
    echo explode(' ', $set['timestamp'])[0] , "-$revenue USD\n";
}
echo "\t== " , number_format((float)$sum, 2, '.', '') , " USD";

输出:

2018-10-26-28.46 USD
2018-10-27-25.71 USD
2018-10-28-29.08 USD
        == 83.25 USD

*请注意,这会继续添加数字格式的值。如果您需要更高的特异性-也就是说,您希望将更长的浮点值相加,然后在末尾仅格式化一次,我也可以对其进行编码。