4

我有以下数组,我使用它输出echo json_encode(array);

Array (
  [0] => Array (
  [id] => 85
  [name] => yeyery
  [area_xy] => {"type": "rectangle","coordinates": {"point1":"22.272219163607744:114.13580417633057","point2":"22.275753627993897:114.1413402557373","point3":"22.27297371968214:114.14400100708008","point4":"22.270868895211578:114.13910865783691"}}
  )
)

这是我得到的输出:

[
   {
      "id":"85",
      "name":"yeyery",
      "area_xy":"{\"type\": \"rectangle\",\"coordinates\": {\"point1\":\"22.272219163607744:114.13580417633057\",\"point2\":\"22.275753627993897:114.1413402557373\",\"point3\":\"22.27297371968214:114.14400100708008\",\"point4\":\"22.270868895211578:114.13910865783691\"}}",
   }
]

但预期的输出是这样的:

[
   {
      "id":"85",
      "name":"yeyery",
      "area_xy":{"type": "rectangle","coordinates": {"point1":"22.272219163607744:114.13580417633057","point2":"22.275753627993897:114.1413402557373","point3":"22.27297371968214:114.14400100708008","point4":"22.270868895211578:114.13910865783691"}},
   }
]

"area_xy"我不想用双引号包裹我的嵌套 JSON 之后。

4

1 回答 1

5

初始输出具有误导性;您应该使用var_export,并且您会看到该area_xy值已经是一个字符串:

array (
  0 => 
  array (
    'id' => 85,
    'name' => 'yeyery',
    'area_xy' => '{"type": "rectangle","coordinates": {"point1":"22.272219163607744:114.13580417633057","point2":"22.275753627993897:114.1413402557373","point3":"22.27297371968214:114.14400100708008","point4":"22.270868895211578:114.13910865783691"}}',
  ),
)

为了纠正这个问题,首先对其进行解码,然后对整个 shebang 进行编码:

$arr[0]['area_xy'] = json_decode($arr[0]['area_xy']);
echo json_encode($arr, JSON_PRETTY_PRINT);
于 2013-07-05T01:19:26.623 回答