带输出的Json_encode()

时间:2012-03-02 18:24:47

标签: php json

难以理解(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"
}

]

}

有人可以帮助我获得类似上面代码的输出吗?

2 个答案:

答案 0 :(得分: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)

在循环之前将项目作为数组创建,追加到循环内部,然后将其放在$ post中并在循环之后对其进行编码。