I am trying to collect an array of data on the three criteria "city", "country", "region". The principle of operation is as follows: consider the user's IP and substitute it in json, after parsing 2 values ​​("city", "country" (region unavailable)) But my code swears at array_merge. Tell me how to do this?

public static function GEO() { $ip = Route::clientIp(); $json = file_get_contents('http://geoip.nekudo.com/api/'.$ip); var_dump($json); $data = json_decode($json, true); $loc = [ 'city' => null, 'country' => null, 'region' => null ]; $location = array_merge($loc, $data); return $location; } 
  • It turned out to parse the "city", but if you parse the country, it displays "a: 2: {s: 4:" name "; s: 6:" Russia "; s: 4:" code "; s: 2:" RU ";}" how to get "name"? - Elizabeth

1 answer 1

Try this:

 public static function GEO() { $ip = Route::clientIp(); $json = file_get_contents('http://geoip.nekudo.com/api/'.$ip); var_dump($json); $data = json_decode($json, true); $location = [ 'city' => null, 'country' => null, 'region' => null ]; $location['city'] = $data['city'] $location['country'] = $data['country']['name'] return $location; } 

Or even easier:

 public static function GEO() { $ip = Route::clientIp(); $json = file_get_contents('http://geoip.nekudo.com/api/'.$ip); var_dump($json); $data = json_decode($json, true); return [ 'city' => $data['city'], 'country' => $data['country']['name'], 'region' => null ]; } 

The fact is that $data['country'] does not contain a value, but another array:

 "name"=>"Russia", "code"=>"RU" 

Therefore, to get to the name , you need to take an array element inside the array:

 $data['country']['name'] 
  • And I need to use this code $ location = array_merge ($ loc, $ data); return $ location ;? Also got out the notice "Notice: Array to string conversion" - Elizaveta
  • I do not quite understand ... I'm doing everything right? public static function GEO () {$ ip = Route :: clientIp (); $ json = file_get_contents (' geoip.nekudo.com/api/'.$ip ); $ data = json_decode ($ json, true); $ loc = ['city' => null, 'country' => null, 'region' => null]; $ loc ['city'] = $ data ['city']; $ loc ['country'] = $ data ['country'] ['name']; $ location = array_merge ($ loc, $ data); return $ location; } - Elizabeth
  • @ Elizabeth, changed the answer - Crantisz
  • Could you send the finished method, otherwise I’m completely confused ( - Elizaveta
  • @ Elizabeth, changed the answer - Crantisz