使用PHP在JSON中细分数据

时间:2013-10-15 03:35:34

标签: php json

如何优雅地将下面的内容转换为JSON,以便“data”(即1,2,3,4和5)中的每个元素都是独立的,并且可以在不使用str_replace或preg_replace的情况下轻松遍历?

{
   "status":"success",
   "data":{
      "1":"this is an element",
      "2":"this is an element",
      "3":"this is an element",
      "4":"this is an element",
      "5":"this is an element",
    }
}

1 个答案:

答案 0 :(得分:4)

假设您已经拥有JSON字符串,请使用json_decode(),并将第二个参数提供为true,以获取已解码JSON的关联数组。

$str = '{"status":"success","data":{"1":"this is an element","2":"this is an element","3":"this is an element","4":"this is an element","5":"this is an element"}}'
$json = json_decode($str, true);

变量$json将是一个关联数组。