【发布时间】:2015-04-30 01:11:50
【问题描述】:
我目前正在使用 JSON 编码的数组在我的数据库中显示标题以实现自动建议功能。
看起来像这样:
<?php
require_once('./includes/config.php');
require_once('./includes/skins.php');
mysql_connect($conf['host'], $conf['user'], $conf['pass']);
mysql_select_db($conf['name']);
$query2012 = sprintf("SELECT * FROM imdb WHERE poster !='posters/noposter.jpg' ORDER BY RAND() DESC LIMIT %d;", 8);
$result = mysql_query($query2012);
//Create an array
$json_response = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$row_array['title'] = $row['title'];
$row_array['year'] = $row['year'];
$row_array['poster'] = $row['poster'];
//push the values in the array
array_push($json_response,$row_array);
}
echo json_encode($json_response);
//Close the database connection
fclose($db);
?>
这会返回:
[{"title":"The Woman","year":"2011","poster":"posters\/tt1714208.jpg"},{"title":"DeadHeads","year":"2011","poster":"posters\/tt1273207.jpg"},{"title":"The Innkeepers","year":"2011","poster":"posters\/tt1594562.jpg"},{"title":"John Carter","year":"2012","poster":"posters\/tt0401729.jpg"},{"title":"American Reunion","year":"2012","poster":"posters\/tt1605630.jpg"},{"title":"The Avengers","year":"2012","poster":"posters\/tt0848228.jpg"},{"title":"Chronicle","year":"2012","poster":"posters\/tt1706593.jpg"},{"title":"Big Miracle","year":"2012","poster":"posters\/tt1430615.jpg"}]
首先,我如何手动添加一个额外的对象到这个输出?例如,假设我想添加:{"status":"ok","message":"Success","data":
{"status":"ok","message":"Success","data":[{"title":"The Woman","year":"2011","poster":"posters\/tt1714208.jpg"},{"title":"DeadHeads","year":"2011","poster":"posters\/tt1273207.jpg"},{"title":"The Innkeepers","year":"2011","poster":"posters\/tt1594562.jpg"},{"title":"John Carter","year":"2012","poster":"posters\/tt0401729.jpg"},{"title":"American Reunion","year":"2012","poster":"posters\/tt1605630.jpg"},{"title":"The Avengers","year":"2012","poster":"posters\/tt0848228.jpg"},{"title":"Chronicle","year":"2012","poster":"posters\/tt1706593.jpg"},{"title":"Big Miracle","year":"2012","poster":"posters\/tt1430615.jpg"}]}
如果没有找到 mysql 记录,则显示 json 输出
{"status":"error","message":"No Reord found"}
如何添加这个?
【问题讨论】: