简体   繁体   English

浏览json并计算值

[英]Browse json and count values

Good night. 晚安。 I'm trying to access all of the availableForExchange values ​​on the return of a page below: 我正在尝试在下面的页面返回时访问所有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
   }
]

I have already tried the following ways: 我已经尝试了以下方法:

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

I need to access all values ​​of: availableForExchange , search for true values ​​and count (if true), and save to a variable. 我需要访问以下所有值: availableForExchange ,搜索真实值并计数(如果为true),然后保存到变量中。

what you want to do is to filter the $json (it is an array) 您想要做的就是过滤$ json(它是一个数组)

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

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

By using array_column to access the availableForExchange values directly, you can use array_filter with no callback (since the values in that column are boolean): 通过使用array_column直接访问availableForExchange值,可以使用不array_filter (因为该列中的值为布尔值):

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

Output (for your sample data) 输出(用于样本数据)

0 available for exchange

Demo on 3v4l.org 3v4l.org上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM