0

I have data as a string, for example:

$a = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';

How to convert it into "key=>value" (associative) array like this :

   ip           => 111.11.1.1
   country      => abc
   country_code => xy
   city         => xxx
dWinder
  • 11,597
  • 3
  • 24
  • 39
Kiran Kumar
  • 167
  • 1
  • 2
  • 13

2 Answers2

2

You can use json-decode and then cast to array:

$str = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';
$arr = (array)json_decode($str);

Or use the assoc flag in json_decode as:

$arr = json_decode($str, true);

Will result in:

array(4) {
  'ip' =>
  string(10) "111.11.1.1"
  'country' =>
  string(3) "abc"
  'country_code' =>
  string(2) "xy"
  'city' =>
  string(3) "xxx"
}
dWinder
  • 11,597
  • 3
  • 24
  • 39
1

You can simply use json_decode() like this

$json = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';
$arr = json_decode($json, true);
print_r($arr);

this will give you the desired result. This will print:

Array ( [ip] => 111.11.1.1 [country] => abc [country_code] => xy [city] => xxx )
Zainul Abideen
  • 1,829
  • 15
  • 37