【问题标题】:How to encode multiple MySQLi result into correct json format?如何将多个 MySQLi 结果编码为正确的 json 格式?
【发布时间】:2015-12-12 01:36:09
【问题描述】:
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"}}]

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

我什至连长时间的观察结果都疯了..

【问题讨论】:

  • (1) 将 $post_data 更改为数组 -> $post_data[] = array(...。 (2) 将您的echo json_encode($post_data); 移到外面/在您的while($row = $result->fetch_assoc()) { 之后
  • 是的!非常感谢!!! :)

标签: php mysql json mysqli formatting


【解决方案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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    • 2017-07-13
    • 2023-03-22
    • 2011-03-22
    • 2016-07-23
    • 1970-01-01
    相关资源
    最近更新 更多