php-字符串到键值(关联)数组类型的转换

时间:2018-11-28 06:39:08

标签: php arrays string key-value

我将数据作为字符串,例如:

$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

2 个答案:

答案 0 :(得分:2)

您可以使用json-decode,然后将其强制转换为数组

$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"
}

答案 1 :(得分:1)

您可以像这样简单地使用LEFT JOIN ( SELECT SUM(Vote) AS UC_Vote, SUM(IF(Vote < 0, Vote, 0)) AS UC_Vote_Neg, SUM(IF(Vote > 0, Vote, 0)) AS UC_Vote_Pos, UC_Code FROM CommentsVote **WHERE cv.UC_Code = com.UC_Code** GROUP BY UC_Code ) AS cv ON cv.UC_Code = com.UC_Code

json_decode()

这将为您提供所需的结果。这将打印:

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