简体   繁体   中英

php numeric array processing

I'm trying to process an array from data posted from a textbox.
I've written the following code to trim each new line and I have nearly everything working perfectly except one thing. I believe I need to iterate my numeric array through this GeoIP function:
$record = geoip_record_by_addr($gi,$value); , but it only processes the last IP in the array, and not the entire thing.

My var_dump: string(12) "65.87.12.213" string(12) "13.15.200.36"

$gi = geoip_open("/tmp/GeoIPCity.dat",GEOIP_STANDARD);

$iips = explode("\n", $_POST["ip"]);
$iiips=array_map('trim',$iips);
foreach($iiips as $key => $value) {
    $record = geoip_record_by_addr($gi,$value);
}
print $record->city . "\n";
print $record->region . " " . "\n";
print $record->country_name . "\n";

$record1 = $record->city . " " . $record->region . " " . $record->country_name;

var_dump($record1);

Is there anybody that can please help?

Inside the foreach loop you overwrite the $record variable all the time, so at the end you have the last one.

Store all records into another array instead and you should be fine.

So this is just a more or less simple mistake you made.

$records = array();
foreach ($iiips as $key=>$value) {
    $records[] = geoip_record_by_addr($gi, $value);
}

foreach ($records as $record) {

    echo $record->city, "\n",
         $record->region, "\n",
         $record->country_name, "\n";

    $record_string = $record->city . " " . $record->region . " " . $record->country_name;

    var_dump($record_string);
}

Instead of $record = geoip_record_by_addr($gi,$value); , do this:

$record = array();
foreach($iiips as $value) { // key isnt needed.
    array_push($record, geoip_record_by_addr($gi,$value));
}

Then you're free to use the contents of $record as you expected. Re-assigning a variable in any loop will change the value of that specific variable each time. PHP doesn't know that you're using an array unless you tell it.

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