2012-01-12 106 views
0

我试着去用PHP编码功能来创建此:JSON编码问题

{ 
"foo": [ 
    { 
    "bar": "111" 
    } 
] 
} 

但所有我可以与一些PHP数组和JSON编码管理是这样的:

{ 
"foo": [ 
    "{ 
     \"bar\":184530" 
    }" 
] 
} 

显然我不t希望将对象当作字符串而不是对象,因此不用引号。

这里是我的PHP:

$stmt->execute(); 
    $stmt->bind_result($bar); 
    while ($stmt->fetch()) { 
     $activity_array = array("bar" => $bar);     
     $activity_json = json_encode($activity_array); 
     $json_array[] = $activity_json; 
    } 

    $json = json_encode($json_array); 
    echo '{ "foo": ' .$json .'}'; 

回答

4

不编码数据结构JSON位。只编码最终的数据结构。删除此行:

$activity_json = json_encode($activity_array); 

即使你有编码为存储在也被编码为JSON阵列JSON阵列。

你想要一个包含数组(不是JSON位)的数组(编码为JSON)。

+0

就是这样,非常感谢!还有:$ json_array [] = $ activity_array; – MaikelS 2012-01-12 14:57:03

+0

'json_encode'返回一个字符串,所以你的“JSON位”只是一个字符串。你只是编码一个字符串数组。 – 2012-01-12 14:57:21

1

json_encode需要一个PHP数组,并将其转换为JSON。你不会像JSON那样构建数组,只需构建一个普通数组,然后json_encode就可以了。

例如,使你的问题的对象,你可以这样做:

$arr = array('foo' => array(
    array('bar' => 111) 
)); 
echo json_encode($arr); 

所以,仅仅建立数组,然后echo json_encode($json_array);

$stmt->execute(); 
$stmt->bind_result($bar); 
while ($stmt->fetch()) { 
    $activity_array = array("bar" => $bar); 
    $json_array[] = $activity_json; 
} 

$json = json_encode(array('foo' => $json_array)); 
echo $json; 
0

您可以使用此little PHP library。它发送标题并为您提供一个可以轻松使用的对象。

它看起来像:

<?php 
// Include the json class 
include('includes/json.php'); 

// Then create the PHP-Json Object to suits your needs 

// Set a variable ; var name = {} 
$Json = new json('var', 'name'); 
// Fire a callback ; callback({}); 
$Json = new json('callback', 'name'); 
// Just send a raw JSON ; {} 
$Json = new json(); 

// Build data 
$object = new stdClass(); 
$object->test = 'OK'; 
$arraytest = array('1','2','3'); 
$jsonOnly = '{"Hello" : "darling"}'; 

// Add some content 
$Json->addContent(new propertyJson('width', '565px')); 
$Json->addContent(new textJson('You are logged IN')); 
$Json->addContent(new objectJson('An_Object', $object)); 
$Json->addContent(new arrayJson("An_Array",$arraytest)); 
$Json->addContent(new jsonJson("A_Json",$jsonOnly)); 

// Finally, send the JSON. 

json_send($Json) 
?>