【问题标题】:PHP How to count the number of items in JSON results but not the total number the number of specific results?PHP如何计算JSON结果中的项目数而不是具体结果的总数?
【发布时间】:2019-12-31 01:26:46
【问题描述】:

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

我想:

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

我可以:

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

我不能:

弄清楚如何计算 API 结果中代表的特定国家/地区的数量。例如,我想得到像“United States: 25”或“Mexico: 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"?

}

【问题讨论】:

  • 你能举个json输出的例子吗?
  • 如果$api_result['country_name'] 是一个字符串,那么你如何获得国家列表?从这个例子中完全不清楚。此处的一般答案是将国家/地区聚合到一个数组中,其中键是国家/地区名称,值是该国家/地区出现在 API 结果中的次数的递增整数。即类似if (isset($countries[$api_result['country_name']])) { $countries[$api_result['country_name']]++; } else { $countries[$api_result['country_name']] = 1; }

标签: php arrays json curl


【解决方案1】:

在您的问题中,来自 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)
    }

    */

【讨论】:

    猜你喜欢
    • 2019-03-02
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 2014-06-16
    • 2023-03-03
    • 2023-03-05
    • 1970-01-01
    • 2014-10-30
    相关资源
    最近更新 更多