-1

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?

Frenck
  • 6,514
  • 5
  • 22
  • 25
  • Google "JSON formatter" and you'll probably find some code to format JSON in PHP. – JW. Mar 02 '12 at 18:28
  • You could try this : http://stackoverflow.com/questions/6054033/pretty-printing-json-with-php – malletjo Mar 02 '12 at 18:29
  • Are you want to match with js json and php json? – Subhojit Mukherjee Mar 02 '12 at 18:29
  • 1
    To current and future answerers/commenters: please note that the structure of what the OP wants and what he has is *not* the same, so it's not a matter of just reformatting the output. – JJJ Mar 02 '12 at 18:30

2 Answers2

8

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

Sahand
  • 2,095
  • 1
  • 19
  • 24
1

Create items as an array before the loop, append inside the loop, then put it in $post and encode it after the loop.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358