php - 字符串到键值(关联)数组类型的转换
php - string to key-value (associative) array type conversion
我有一个字符串数据,例如:
$a = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';
如何将其转换为 "key=>value"(关联)数组,如下所示:
ip => 111.11.1.1
country => abc
country_code => xy
city => xxx
您可以使用 json-decode 然后转换为 array:
$str = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';
$arr = (array)json_decode($str);
或者使用 json_decode 中的 assoc
标志作为:
$arr = json_decode($str, true);
将导致:
array(4) {
'ip' =>
string(10) "111.11.1.1"
'country' =>
string(3) "abc"
'country_code' =>
string(2) "xy"
'city' =>
string(3) "xxx"
}
您可以像这样简单地使用 json_decode()
$json = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';
$arr = json_decode($json, true);
print_r($arr);
这会给你想要的结果。这将打印:
Array ( [ip] => 111.11.1.1 [country] => abc [country_code] => xy [city] => xxx )
我有一个字符串数据,例如:
$a = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';
如何将其转换为 "key=>value"(关联)数组,如下所示:
ip => 111.11.1.1
country => abc
country_code => xy
city => xxx
您可以使用 json-decode 然后转换为 array:
$str = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';
$arr = (array)json_decode($str);
或者使用 json_decode 中的 assoc
标志作为:
$arr = json_decode($str, true);
将导致:
array(4) {
'ip' =>
string(10) "111.11.1.1"
'country' =>
string(3) "abc"
'country_code' =>
string(2) "xy"
'city' =>
string(3) "xxx"
}
您可以像这样简单地使用 json_decode()
$json = '{"ip":"111.11.1.1","country":"abc","country_code":"xy","city":"xxx"}';
$arr = json_decode($json, true);
print_r($arr);
这会给你想要的结果。这将打印:
Array ( [ip] => 111.11.1.1 [country] => abc [country_code] => xy [city] => xxx )