Loop不使用完整IP,而只使用第一个数字

mar*_*ijn 2 php loops

我正在尝试获取数据库中每个ip的位置现在问题是它只使用第一个数字而不是完整的ip由于某种原因所以我得到错误:

警告:file_get_contents(ipinfo.io/8):无法打开流:HTTP请求失败!找不到HTTP/1.1 404

现在是我的问题,我怎么能使它与完整的IP工作,因为我不再有线索了.

$result_ip = $dbhandle->query("SELECT ip FROM email");
$row_cnt_ip = $result_ip->num_rows;
$ip_rows = $result_ip->fetch_array(MYSQLI_ASSOC);
$country_ip_data = array();

foreach ($ip_rows as $ip_row) {
    $ip = $ip_row['ip'];
    if (!$ip) {
        continue;
    }
    $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
    $country = $details->country;
    if (!isset($country_ip_data[$country])) {
        $country_ip_data[$country] = array();
    }
    $country_ip_data[$country][] = $ip;
}

var_dump($country_ip_data);
Run Code Online (Sandbox Code Playgroud)

最终结果应该是包含所有国家/地区的数组,以便我可以在每个国家/地区对其进行过滤并将其放入地图中.

Ant*_*ton 5

问题就在于此$ip_rows = $result_ip->fetch_array(MYSQLI_ASSOC);.mysqli fetch_array方法从查询的数据中返回一行,因此您需要循环遍历所有行:

$result_ip = $dbhandle->query("SELECT ip FROM email");
$row_cnt_ip = $result_ip->num_rows;
$country_ip_data = array();

// use a while loop to extract one row's data at a time
while ($ip_row = $result_ip->fetch_array(MYSQLI_ASSOC)) {
    $ip = $ip_row['ip'];
    if (!$ip) {
        continue;
    }
    $details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
    $country = $details->country;
    if (!isset($country_ip_data[$country])) {
        $country_ip_data[$country] = array();
    }
    $country_ip_data[$country][] = $ip;
}

var_dump($country_ip_data);
Run Code Online (Sandbox Code Playgroud)