【问题标题】:How to encode json with multiple rows?如何用多行编码json?
【发布时间】:2018-08-02 15:32:00
【问题描述】:

在开始之前,我查看了多个平台上的其他示例和问答,但似乎都没有解决我的问题。我正在尝试通过 json 从 MySQL 返回多行。然而,我一直做不到。下面的代码显示了我的尝试。

我通过 Postman 收到回复。第一个 while 仅返回数据库中的最后一个条目,do-while 返回所有条目但未正确编码 json,因为 json 输出 syntax error 但 html 部分显示所有条目。

<?php
    $dashboard_content_token = $_REQUEST["dashboard_content_token"];
    $token = "g4";

    require(cc_scripts/connect.php);

    $sql = "SELECT * FROM `dashboard_content`";
    $check = strcmp("$token", "$dashboard_content_token");
    $statement = mysqli_query($con, $sql);
    if (check) {
        $rows = mysqli_fetch_assoc($statement);
        if (!$rows) {
            echo "No results!";
        } else {
              while ($rows = mysqli_fetch_assoc($statement)) {
                $news_id = $rows['news_id'];
                $image_url = $rows['image_url'];
                $news_title = $rows['news_title'];
                $news_description = $rows['news_description'];
                $news_article = $rows['news_article'];

                $result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article); 

                echo json_encode($result);
        }
        // do {
                // $news_id = $rows['news_id'];
                // $image_url = $rows['image_url'];
                // $news_title = $rows['news_title'];
                // $news_description = $rows['news_description'];
                // $news_article = $rows['news_article'];

                // $result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article); 

                // echo json_encode($result);
        //     } while ($rows = mysqli_fetch_assoc($statement));


        mysqli_free_result($statement);
    }
}
?>

【问题讨论】:

  • 我想你想在这里使用do-while。否则将跳过第一个结果。数据库中只有两个结果吗?
  • 您可能会遇到语法错误,因为您多次回显json_encode()。如果将所有数据库条目添加到 $result 数组并在 do-while 循环之后执行一个 echo json_encode($result); 会怎样?
  • 现在是的,我只有两个。以后我仍然会用更多的东西淹没我的数据库。 do-while 没有正确编码 json。
  • @joeljoeljoel 您的建议效果很好,希望发布答案和解释,以防其他人。另外,我可以标记它,你会得到一些声誉。
  • @joeljoeljoel 它刚刚击中了我,但你怎么知道我的数据库中只有 2 个条目?

标签: php json


【解决方案1】:

这应该可行。您需要使用 do...while 语句,否则会跳过第一个结果。

<?php
    $dashboard_content_token = $_REQUEST["dashboard_content_token"];
    $token = "g4";

    require(cc_scripts/connect.php);

    $sql = "SELECT * FROM `dashboard_content`";
    $check = strcmp("$token", "$dashboard_content_token");
    $statement = mysqli_query($con, $sql);
    if (check) {
        $rows = mysqli_fetch_assoc($statement);
        if (!$rows) {
            echo "No results!";
        } else {

          do {
             $news_id = $rows['news_id'];
             $image_url = $rows['image_url'];
             $news_title = $rows['news_title'];
             $news_description = $rows['news_description'];
             $news_article = $rows['news_article'];

               $result['dashboard content: '][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article); 


          } while ($rows = mysqli_fetch_assoc($statement));

        mysqli_free_result($statement);
        echo json_encode($result);
    }
}
?>

关键是将所有结果放入一个数组中,然后只做一个json_encode()。当您多次调用json_encode() 时,您的API 将返回无效的json。

【讨论】:

  • 你能做同样的事情,但使用准备好的语句吗?
【解决方案2】:

在你的 while 循环中,

$result['dashboard content: '] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article); 

每次运行循环时,只需在 $result 数组中覆盖相同的“仪表板内容”条目。这就是为什么您只看到最后一个条目的原因。

在循环中执行 json_encode() 也没有任何意义,因为您只会输出多个不连贯的单个 JSON 对象,它们不是数组或连贯结构的一部分。这不会产生有效的 JSON 响应。

目前还不清楚您希望得到什么样的输出结构,但这可能会给您一个解决方案,或者至少是朝着正确的方向推进:

$statement = mysqli_query($con, $sql);
$result = array("dashboard_content" => array()); //create an associative array with a property called "dashboard_content", which is an array. (json_encode will convert an associative array to a JSON object)

if (check) {
    $rows = mysqli_fetch_assoc($statement);
    if (!$rows) {
        echo "No results!";
    } else {
          while ($rows = mysqli_fetch_assoc($statement)) {
            $news_id = $rows['news_id'];
            $image_url = $rows['image_url'];
            $news_title = $rows['news_title'];
            $news_description = $rows['news_description'];
            $news_article = $rows['news_article'];

            //append the current data to a new entry in the "dashboard_content" array
            $result["dashboard_content"][] = array('news_id' => $news_id, 'image_url' => $image_url, 'news_title' => $news_title, 'news_description' => $news_description, 'news_article' => $news_article); 
        }
    }

    //now, output the whole completed result to one single, coherent, valid JSON array.
    echo json_encode($result);

你应该得到一些像这样的 JSON:

{
  "dashboard_content": [
    {
      "news_id": 1,
      "image_url": "abc",
      "news_title": "xyz",
      //...etc
    },
    {
      "news_id": 2,
      "image_url": "def",
      "news_title": "pqr",
      //...etc
    },
    //...etc
  ]
}

【讨论】:

  • 感谢您的回答,您确实是正确的。但是其他人已经在 cmets 中解决了我的问题,我正在等待他发布正确的答案以便我接受。
猜你喜欢
  • 2019-09-09
  • 2013-09-18
  • 1970-01-01
  • 2012-03-10
  • 1970-01-01
  • 2014-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多