encode() with output
Hard to understand (json_encode) i'm using the code:
<?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);
}
?>
Output:
{"items":[{"title":"title","description":"title"}]}
{"items":[{"title":"title","description":"title"}]}
But i want an output like:
{
"items": [
{
"title":"title",
"description":"title"
},
{
"title":"title",
"description":"title"
},
{
"title":"title",
"description":"title"
}
]
}
Can someone please help me to get an output like the code above?
Try this instead:
<?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);
?>
Edit: correction
在循环之前将项目创建为数组,在循环内部追加,然后将其放入$ post并在循环之后进行编码。
链接地址: http://www.djcxy.com/p/47280.html上一篇: 如何从PHP文件输出格式正确的JSON?
下一篇: 用输出编码()