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
0

2 Answers 2

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"
}
Sign up to request clarification or add additional context in comments.

3 Comments

thank you so much. This is what I am looking for ...
@KiranKumar You welcome - if my post help you please mark it as accepted
Yes, I've Accepted ...
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 )

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.