我确信这已经被问到1000倍,但由于某些原因,我找不到一个解释它的方式,我可以理解,并得到正确的工作。我很难表达我想要得到答案的问题,所以如果你能帮忙的话,我很感激你的帮助。
我想:
计算在IP地址数组的API查询中表示的国家数。
我可以:
查询API并获得包含国家的每个IP地址的结果。
我不能:
计算出如何在API结果中表示特定国家的多少。例如,Id希望得到“美国: 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"?
}发布于 2019-12-31 01:42:12
在您的问题中,还不完全清楚来自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)
}
*/https://stackoverflow.com/questions/59538588
复制相似问题