从API获取多个值并将其相加

时间:2018-07-27 05:31:23

标签: php api

所以,我有这个网站上的这个api(不是我的网站,也没有访问文件的权限)

以下是api的响应:

{
  "previousPageCursor": null,
  "nextPageCursor": null,
  "data": [
    {
      "userAssetId": 413511366,
      "serialNumber": null,
      "assetId": 1028606,
      "name": "Red Baseball Cap",
      "recentAveragePrice": 271,
      "originalPrice": null,
      "assetStock": null,
      "buildersClubMembershipType": 0
    },
    {
      "userAssetId": 1075234337,
      "serialNumber": 820,
      "assetId": 93131552,
      "name": "Dark Conjurer",
      "recentAveragePrice": 59910,
      "originalPrice": 250,
      "assetStock": 900,
      "buildersClubMembershipType": 0
    },
    {
      "userAssetId": 4506314814,
      "serialNumber": 944,
      "assetId": 439946101,
      "name": "Adurite King of the Night ",
      "recentAveragePrice": 9805,
      "originalPrice": 100,
      "assetStock": 2000,
      "buildersClubMembershipType": 0
    },
    {
      "userAssetId": 4779382222,
      "serialNumber": null,
      "assetId": 71484026,
      "name": "Sinister Branches",
      "recentAveragePrice": 2223,
      "originalPrice": 125,
      "assetStock": null,
      "buildersClubMembershipType": 0
    },
    {
      "userAssetId": 20445168513,
      "serialNumber": 4667,
      "assetId": 1609401184,
      "name": "Supa Dupa Fly Cap",
      "recentAveragePrice": 5488,
      "originalPrice": 1000,
      "assetStock": 10000,
      "buildersClubMembershipType": 0
    }
  ]
}

我想从api中获取所有“ recentAveragePrice”值,然后将这些值添加到php中,但我无法弄清楚。

1 个答案:

答案 0 :(得分:0)

尝试一下:

$responseJson = '{"previousPageCursor":null,"nextPageCursor":null,"data":[{"userAssetId":413511366,"serialNumber":null,"assetId":1028606,"name":"Red Baseball Cap","recentAveragePrice":271,"originalPrice":null,"assetStock":null,"buildersClubMembershipType":0},{"userAssetId":1075234337,"serialNumber":820,"assetId":93131552,"name":"Dark Conjurer","recentAveragePrice":59910,"originalPrice":250,"assetStock":900,"buildersClubMembershipType":0},{"userAssetId":4506314814,"serialNumber":944,"assetId":439946101,"name":"Adurite King of the Night ","recentAveragePrice":9805,"originalPrice":100,"assetStock":2000,"buildersClubMembershipType":0},{"userAssetId":4779382222,"serialNumber":null,"assetId":71484026,"name":"Sinister Branches","recentAveragePrice":2223,"originalPrice":125,"assetStock":null,"buildersClubMembershipType":0},{"userAssetId":20445168513,"serialNumber":4667,"assetId":1609401184,"name":"Supa Dupa Fly Cap","recentAveragePrice":5488,"originalPrice":1000,"assetStock":10000,"buildersClubMembershipType":0}]}';

$responseArr = json_decode($responseJson, true);
echo array_sum(array_column($responseArr['data'], 'recentAveragePrice'));

eval.in demo

这首先使用json_decode将JSON转换为PHP数组(true的第二个参数使它成为数组而不是对象),然后使用array_column获得{ recentAveragePrice的{​​1}}列,最后使用array_sum对该数组求和。