如何从mysql数据库创建json文件?

时间:2017-10-05 10:12:07

标签: mysql json encoding

我想创建一个json文件。

$data = $db->query('SELECT * FROM data ORDER BY id ASC;')->fetchAll(PDO::FETCH_ASSOC);
$json_string = json_encode($data);
$file = 'data.json';
file_put_contents($file, $json_string);

我的结果:

[{
    "id": "123",
    "timestamp": "2017-05-12 16:22:39",
    "name": "bear",
    "description": "dance all day"
    },
  ....
}]

但我实际需要的格式是:

{
  "data": [
    [
      "123",
      "2017-05-12 16:22:39",
      "bear",
      "dance all day"
    ],
  ....
  ]
}

1 个答案:

答案 0 :(得分:1)

您可以这样做:

$results= $db->query('SELECT * FROM data ORDER BY id ASC;')->fetch_all();

$data = array();
foreach ($results as $row) {
    $id = $row[0];
    $timestamp = $row[1];
    $name = $row[2];
    $description = $row[3];
    $data[] = array($id, $timestamp, $name, $description);
}
$json = json_encode(array("data" => $data));