2012-03-02 51 views
-1

很难理解(json_encode):Json_encode()与我正在使用的代码输出

<?php 

    $query = mysql_query("SELECT * FROM messages ORDER BY ID"); 
    while($fetch = mysql_fetch_assoc($query)) 
    { 
    $titel = $fetch[title]; 
    $post = array('items' => array(0 => array('title' => "$title", 'description' => "$title"))); 


    echo json_encode($post); 

} 
?> 

输出:

{"items":[{"title":"title","description":"title"}]} 
{"items":[{"title":"title","description":"title"}]} 

但我想等的输出:

{ 

"items": [ 

{ 
"title":"title", 
"description":"title" 
}, 
{ 
"title":"title", 
"description":"title" 
}, 
{ 
"title":"title", 
"description":"title" 
} 

] 

} 

有人可以帮助我得到像上面的代码输出?

+0

谷歌 “JSON格式”,你可能会发现一些代码在PHP格式化JSON。 – 2012-03-02 18:28:37

+0

你可以试试这个:http://stackoverflow.com/questions/6054033/pretty-printing-json-with-php – malletjo 2012-03-02 18:29:15

+0

你想匹配js json和php json吗? – 2012-03-02 18:29:15

回答

8

试试这个:

<?php 

$query = mysql_query("SELECT * FROM messages ORDER BY ID"); 
$post = array(); 
while($fetch = mysql_fetch_assoc($query)) 
{ 
    $titel = $fetch[title]; 
    $post['items'][] = array('title' => "$title", 'description' => "$title"); 
} 
echo json_encode($post); 
?> 

编辑:校正

+1

+1我误解了他的问题,并且你发现了它。 – AlienWebguy 2012-03-02 18:30:10

1

创建的项目,如循环之前的数组,追加内循环,然后把它放在$柱和循环后进行编码。