加總從 php curl 來的數據?

請問一下
我透過 php curl 向對方取得對方數據庫的數據(對方都是給我json)
例如我取出後用 foreach 印出
假設某個欄位

foreach ($xxx->{'xxx'} as $key){
   echo $key->{'xxx-price'};
}

我要怎麼把該array中所有的 $key->{'xxx-price'}加總?
我知道mysql怎麼做
但是用curl我不知道怎麼加總?

阅读 2.3k
3 个回答

第一种:先取要进行统计的key,然后array_sum()

$priceTotal = array_sum(array_column($xxx,'price'));

第二种:

$priceTotal = 0;
foreach($xxx as $item) {
    $priceTotal += $item['price'];
}
echo $priceTotal;

看你喜欢用哪一种了

<?php
$a = array(
  array(
    'id' => 5698,
    'first_name' => 'Bill',
    'last_name' => 'Gates',
  ),
  array(
    'id' => 4767,
    'first_name' => 'Steve',
    'last_name' => 'Jobs',
  ),
  array(
    'id' => 3809,
    'first_name' => 'Mark',
    'last_name' => 'Zuckerberg',
  )
);

$id = array_column($a, 'id');
print_r($id);
?>

Array
(
  [0] => 5698
  [1] => 4767
  [2] => 3809
)
array_sum($id)

14274

json_decode($json, true);

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题