如何在php mysqli中生成json对象

时间:2017-03-18 05:05:27

标签: php json string mysqli

我可以用PHP中的MYSQLi查询生成这个JSON吗?

{
    "name": "Top Node",
    "children": [
      {
        "name": "Bob: Child of Top Node",
        "parent": "Top Node",
        "children": [
          {
            "name": "Son of Bob",
            "parent": "Bob: Child of Top Node"
          },
          {
            "name": "Daughter of Bob",
            "parent": "Bob: Child of Top Node"
          }
        ]
      },
      {
        "name": "Sally: Child of Top Node",
        "parent": "Top Node"
      }
    ]
  }

1 个答案:

答案 0 :(得分:0)

您可以使用 json_encode 对sql查询中的结果进行编码。

示例:

    $rows = array();
    while ($r = mysqli_fetch_array("SELECT * FROM TABLE_NAME", MYSQLI_ASSOC)) {
        $rows[] = $r;
    }
    echo json_encode($rows);  //print result in json format