首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP如何计算JSON结果中的项目数,而不是总数、特定结果的数量?

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

Stack Overflow用户
提问于 2019-12-31 01:26:46
回答 1查看 95关注 0票数 1

我确信这已经被问到1000倍,但由于某些原因,我找不到一个解释它的方式,我可以理解,并得到正确的工作。我很难表达我想要得到答案的问题,所以如果你能帮忙的话,我很感激你的帮助。

我想:

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

我可以:

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

我不能:

计算出如何在API结果中表示特定国家的多少。例如,Id希望得到“美国: 25”或“墨西哥: 7”这样的输出

我有:

一个IP地址数组

一系列国家的名字

代码语言:javascript
复制
$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"?

}
EN

回答 1

Stack Overflow用户

发布于 2019-12-31 01:42:12

在您的问题中,还不完全清楚来自API的JSON是什么样子,所以我只能根据API返回包含每个请求的国家列表的想法,粗略地给出一个大致的答案。

代码语言:javascript
复制
    <?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)
    }

    */
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59538588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档