2012-01-12 100 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) 
?>