繁体   English   中英

PHP如何计算JSON结果中的项目数而不是特定结果的总数?

[英]PHP How to count the number of items in JSON results but not the total number the number of specific results?

我确定这已被问到 1000 倍,但由于某种原因,我找不到以我可以理解并正常工作的方式解释它的答案。 我无法表达我试图回答的问题,所以如果你能提供帮助,我很感激你的帮助。

我想要:

计算 IP 地址数组的 API 查询中表示的国家/地区数量。

我可以:

查询 API 并获取包含国家/地区的每个 IP 地址的结果。

我不能:

弄清楚如何计算 API 结果中代表特定国家/地区的数量。 例如,我想得到类似“美国:25”或“墨西哥:7”的输出

我有:

一组IP地址
一组国家名称

$ip = array(array of ip addresses);
$countries = array(array of countries);

foreach ($ip as $address) {

// Initialize CURL:
$ch = curl_init('http://api.ipstack.com/'.$address.'?access_key='.$access_key.'');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Store the data:
$json = curl_exec($ch);
curl_close($ch);

// Decode JSON response:
$api_result = json_decode($json, true);

# the api result for country name, a list of countries one for each ip address
$country_name = $api_result['country_name'];
echo $country_name . '<br />';

# how do i find out how many of those results are "United States"?

}

不完全清楚来自 API 的 JSON 在您的问题中是什么样子的,因此我只能根据 API 返回每个请求的国家/地区列表这一想法,粗略地给您一个一般性的答案。

    <?php
    /*
       First initialize an empty array of countries to keep track of how many
       times each country appears. This means the key is the country name and the value
       is an integer that will be incremented each time we see it in the API result
    */
    $countries = [];

    // Next get the result from your API let's assume it's an array in $apiResult['countries']
    foreach ($apiResult['countries'] as $country) {
        if (isset($countries[$country])) { // we've already seen it at least once before
            $countries[$country]++; // increment it by 1
        } else { // we've never seen it so let's set it to 1 (first time we've seen it)
            $countries[$country] = 1; // Set it to 1
        }
    }


    /*
       Do this in a loop for every API result and in the end $countries
       should have what you want

    array(2) {
      ["United States"]=>
      int(3)
      ["Mexico"]=>
      int(2)
    }

    */

暂无
暂无

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

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