2014-01-29 81 views
1

我想要生成一个使用PHP传递给客户端使用已存储在MySQL数据库中的数据的JSON对象。从多维数组创建一个JSON对象存储为字符串

该数据库包含多面的坐标列表象下面这样一个文本字段:

[ 
    [ 
     [ 
      [ 
       104.39209000000005, 
       -4.850154 
      ], 
      [ 
       108.17138687500005, 
       -3.721745195827911 
      ], 
      [ 
       112.12646500000005, 
       -1.274309 
      ], 
      [ 
       103.02978499999995, 
       -3.579213 
      ] 
     ] 
    ] 
] 

当我尝试生成一个使用JSON对象json_encode我得到如下:

{ 
    "coordinates": "[[[[104.39209000000005,-4.850154],[108.17138687500005,-3.721745195827911],[112.12646500000005,-1.274309],[103.02978499999995,-3.579213]]]]" 
} 

而且由于围绕坐标本身的引号,它们不被JavaScript识别为JSON对象。

我试图展开坐标字符串,然后手动放回到一起,但它仍然需要大量的黑客才能使其工作。 任何帮助在PHP中获取它作为实际的JSON对象输出将不胜感激。

我试图去这样的:

{ 
    "coordinates": [ 
     [ 
      [ 
       [ 
        104.39209000000005, 
        -4.850154 
       ], 
       [ 
        108.17138687500005, 
        -3.721745195827911 
       ], 
       [ 
        112.12646500000005, 
        -1.274309 
       ], 
       [ 
        103.02978499999995, 
        -3.579213 
       ] 
      ] 
     ] 
    ] 
} 
+1

**显示php代码**,你是如何从数据库中获取数据的,你如何将它分配给一个变量? –

+1

你可以简单地通过'JSON.parse()'来提供你的字符串吗? – Scuzzy

+1

或者通过服务器端的['json_decode'](http://us2.php.net/json_decode)。 – user113215

回答

0

这是非常杰里 - 操纵,但你可以这样做:

$string = json_encode($database_value); // same as you're using now 
$string = str_replace('"', '', $string); // get rid of the quotes 

// wrap them back around 'coordinates' 
$string = str_replace('coordinates', '"coordinates"', $string); 
0

只需json_encode使用前json_decode,像这样:

// This comes from the database, of course 
$coords = '[[[[104.39209000000005,-4.850154],[108.17138687500005,-3.721745195827911],[112.12646500000005,-1.274309],[103.02978499999995,-3.579213]]]]'; 

echo json_encode(array(
    'coordinates' => json_decode($coords) 
)); 

这将完全按照您的愿望输出嵌套阵列:

{"coordinates":[[[[104.39209,-4.850154],[108.171386875,-3.7217451958279],[112.126465,-1.274309],[103.029785,-3.579213]]]]} 
+1

为什么downvote,有什么不对? –

相关问题