PHP从json或数组计算值

时间:2017-03-29 11:42:12

标签: php

我正在阅读一份打印出来的文件。

    {  
   "draw":0,
   "recordsTotal":3995,
   "recordsFiltered":1,
   "data":[  
      {  
         "customer_id":"1",
         "channel":"2",
         "date":"2017-03\/21 ",
         "earnings":"2500"
      },
      {  
         "customer_id":"2",
         "channel":"2",
         "date":"2017-03\/21 ",
         "earnings":"1500"
      }
   ]
}

是否可以在单独的php文件中阅读此内容并计算总收入?

2500 + 1500 = 4000

1 个答案:

答案 0 :(得分:3)

试试这个:

$decoded = json_decode($json, true); // Decode JSON to array

echo array_sum(array_column($decoded['data'], 'earnings')); // Calculate sum of 'earnings' index within 'data'