问题
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
回答1:
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"
}
回答2:
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 )
来源:https://stackoverflow.com/questions/53513541/php-string-to-key-value-associative-array-type-conversion