简体   繁体   中英

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

Im sure this has been asked a 1000x but for some reason I cant find an answer that explains it in a way that I can understand and get to work properly. Im having trouble expressing the question Im trying to get answered, so I appreciate your help if you can help.

I want to:

Count the number of countries represented in an API query of an array of IP addresses.

I can:

Query the API and get a result for each IP address that includes the country.

I cant:

Figure out how to count how many of a specific country is represented in the API results. For example, Id like to get an output like "United States: 25" or "Mexico: 7"

I have:

An array of IP address
An array of countries names

$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"?

}

It's not entirely clear what the JSON coming from the API looks like in your question so I can only give you a general answer loosely based on the idea that the API returns a list of countries with each request.

    <?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)
    }

    */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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