浏览json并计算值

时间:2019-01-23 21:45:32

标签: php

晚安。 我正在尝试在下面的页面返回上访问所有availableForExchange值:

[
   {
      "code":"18707498",
      "date":"2019-01-23T16:58:01",
      "totalPriceInCents":14450,
      "orderTotalPriceInCents":14450,
      "status":"PGTO_NAO_CONFIRMADO",
      "availableForExchange":false,
      "paymentType":"CREDIT_CARD",
      "installmentValueInCents":7225,
      "installmentsNumber":2,
      "paymentSummaries":[
         {
            "paymentType":"CREDIT_CARD",
            "installmentsNumber":2,
            "installmentValueInCents":7225,
            "valueInCents":14450
         }
      ],
      "hasGiftCard":false
   },
   {
      "code":"019741817156",
      "date":"2017-06-11T19:09:06",
      "totalPriceInCents":19110,
      "orderTotalPriceInCents":19110,
      "status":"ENTREGA_EFETUADA",
      "availableForExchange":false,
      "paymentType":"CREDIT_CARD",
      "installmentValueInCents":9555,
      "installmentsNumber":2,
      "paymentSummaries":[
         {
            "paymentType":"CREDIT_CARD",
            "installmentsNumber":2,
            "installmentValueInCents":9555,
            "valueInCents":19110
         }
      ],
      "hasGiftCard":false
   }
]

我已经尝试了以下方法:

$data = curl_exec($ch);
$json = json_decode($data, true);
$str = $json['availableForExchange'];
print_r($str);

我需要访问availableForExchange的所有值,搜索真值并计数(如果为真), 并保存到变量中。

2 个答案:

答案 0 :(得分:4)

您要做的是过滤$ json(它是一个数组)

$found = array_filter($json, function($entry) { return $entry['availableForExchange']; });

echo 'Entries: '.count($found);
print_r($found);

答案 1 :(得分:3)

通过使用array_column直接访问availableForExchange的值,您可以使用array_filter而不进行回调(因为该列中的值是布尔值):

$json = json_decode($data, true);
$available = count(array_filter(array_column($json, 'availableForExchange')));
echo "$available available for exchange\n";

输出(用于示例数据)

0 available for exchange

Demo on 3v4l.org