在JSON中添加其他对象

时间:2015-02-27 10:42:26

标签: php mysql arrays json

我目前正在使用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"}

我怎么能添加这个?

1 个答案:

答案 0 :(得分:1)

您可以在编码之前将其添加到$ json_response数组(json_encode(),方法是修改它:

$json_response = array(
    'data' => $json_response,
    'status' => 'ok',
    'message' => 'Successs'
);

您还可以修改追加数据到最终结果变量,以便在定义$ json_response数组时添加子数组:

$json_response = array('data' => array());

并在while循环中添加索引数据

array_push($json_response['data'], $row_array);

在循环之后,您可以通过以下方式轻松附加您的状态和消息:

$json_response['status'] = 'ok';
$json_response['message'] = 'Success';

要添加错误,请检查数据数组是否为空。对于第一个解决方案:

if (empty($json_response)) {
    $json_response = array(
        'status' => 'error',
        'message' => 'No Reord found'
    );
} else {
    //  here append success message
}

在第二种情况下,只需将if条件更改为:

if (empty($json_response['data']))