如何将多个MySQLi结果编码为正确的json格式?

时间:2015-09-15 17:24:09

标签: php mysql json mysqli formatting

if ($result->num_rows > 0) {

     // output data of each row
     while($row = $result->fetch_assoc()) {

$post_data = array(
    'item' => array(
    'ID' => $row["id"],
    'Name' => $row["name"],
    'Category' => $row["category"],
    'Saldo' => $row["saldo"],
    'Editor' => $row["editor"],
    'Edited' => $row["reg_date"]
  )
);
echo json_encode($post_data);

输出:

{"item":{"ID":"123456","Name":"Chair","Category":"Trashes","Saldo":"40","Editor":"Seppo","Edited":"2015-09-15 13:54:36"}}{"item":{"ID":"123888","Nimi":"Cheese","Kategoria":"Food","Saldo":"3","Editor":"Jorma","Edited:"2015-09-15 14:14:17"}}

什么时候看起来应该是这样的:

[{"item":{"ID":"123456","Name":"Chair","Category":"Trashes","Saldo":"40","Editor":"Seppo","Edited":"2015-09-15 13:54:36"}},{"item":{"ID":"123888","Nimi":"Cheese","Kategoria":"Food","Saldo":"3","Editor":"Jorma","Edited:"2015-09-15 14:14:17"}}]

哪种格式不正确。我应该如何编辑该代码,以便我的所有mysql项目都通过。

即使是很长时间的结果也让我无法理解......

1 个答案:

答案 0 :(得分:1)

您正在重复每次迭代中的$ post_data。你应该追加它。

if ($result->num_rows > 0) 
{
    while($row = $result->fetch_assoc()) 
    {
        $post_data[] = array(
            'item' => array(
                'ID' => $row["id"],
                'Name' => $row["name"],
                'Category' => $row["category"],
                'Saldo' => $row["saldo"],
                'Editor' => $row["editor"],
                'Edited' => $row["reg_date"]
            )
        );
    }

    echo json_encode($post_data);
}