0

我正在使用 jQuery Upload File 插件并尝试将数据库集成到它。我需要像这样输出 json 响应的正确格式:

{"files": [
  {
    "id": 1,
    "name": "picture1.jpg"
  },
  {
    "id": 2,
    "name": "picture2.jpg"
  }
]}

我目前拥有的:

[
  {
    "id": 1,
    "name": "picture1.jpg"
  },
    "id": 2,
    "name": "picture2.jpg"
  }
]

我的 php 文件如下所示:

$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");

foreach ($query as $row) {   
  $file = new stdClass();
  $file->id = $row->id;
  $file->name = $row->name;
  array_push($files,$file);
}

header('Content-type: application/json');
echo json_encode($files);
4

2 回答 2

1
$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");

foreach ($query as $row) {   
  $file = new stdClass();
  $file->id = $row->id;
  $file->name = $row->name;
  array_push($files,$file);
}

header('Content-type: application/json');
echo json_encode(array('files' => $files));
于 2015-05-09T20:24:03.773 回答
0
$t = '[{"id": 1,  "name": "picture1.jpg"}, {"id": 2, "name": "picture2.jpg"}]';

$t = json_decode($t, true);
$t = array("files" => $t);

echo json_encode($t);

输出:

{"files":[{"id":1,"name":"picture1.jpg"},{"id":2,"name":"picture2.jpg"}]}

或者使用您的代码只需执行以下操作:

$files= array();
$db = new DB;
$query = $db->get_rows("SELECT * FROM `files` ORDER BY `name`");

foreach ($query as $row) {   
  $file = new stdClass();
  $file->id = $row->id;
  $file->name = $row->name;
  array_push($files,$file);
}

header('Content-type: application/json');
echo json_encode(array("files" => $files));
于 2015-05-09T20:01:16.540 回答