Reputation: 568
I'm trying to split al the ip's in the database into different arrays based on country, so far i've got this. Now its only taking the first IP of the results out of the query which leads to all the results being the same but i want to get every time a IP got played to move to the next one.
I've tried to use a for loop but that didn't work either since it gave me over 550 results but there are only 24 rows in this test DB.
What is a good way to do this? I think it still should be a for each or something like that but i didnt find the right solution yet.
$result_ip = $dbhandle->query("SELECT ip FROM email");
$row_cnt_ip = $result_ip->num_rows;
$NL = array('');
$AL = array('');
$DE = array('');
$NO_EU = array('');
$row=$result_ip->fetch_assoc();// fetch data
$ip=$row['ip'];
$details = json_decode(file_get_contents("http://ipinfo.io/{$ip}"));
$result_ip->data_seek(0);
while($r = $result_ip->fetch_array(MYSQLI_ASSOC)):
switch ($details->country) {
case "NL": //Netherlands
array_push($NL,"$details->country");
break;
case "AL": //Albania
array_push($AL,"$details->country");
break;
default;
array_push($NO_EU,"no-eu");
break;
}
endwhile;
Upvotes: 1
Views: 55
Reputation: 4105
I'd make a single array keyed by country using a foreach
loop over the DB results. Something like:
<?php
$result_ip = $dbhandle->query("SELECT ip FROM email");
$row_cnt_ip = $result_ip->num_rows;
$ip_rows = $result_ip->fetch_all(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);
Upvotes: 1