php - string to key-value (associative) array type conversion [duplicate]

若如初见. 提交于 2019-12-11 23:13:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!