向JSON添加新行

时间:2013-06-06 21:54:51

标签: php json

我已成功从数据库中获取内容并以JSON格式输出结果。但我想添加一个在数据库中不存在的文本,它就在这里我被卡住了。

$statement = $sql->prepare("SELECT data_filename,
                                   data_filetype,
                                   data_uniqid,
                                   data_description,
                                   data_coordinates,
                                   exif_taken,
                                   exif_camera,
                                   exif_camera_seo,
                                   exif_resolution,
                                   exif_sensitivity,
                                   exif_exposure,
                                   exif_aperture,
                                   exif_focallength,
                                   is_downloadable,
                                   is_notaccurate,
                                   allow_fullsize

                            FROM photos
                            WHERE data_filename = 'P1170976'");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);

$json = json_encode($results);

echo $json;

那段代码给了我

[{"data_filename":"P1170976","data_filetype":"JPG","data_uniqid":"","data_description":"","data_coordinates":"","exif_taken":"0000-00-00","exif_camera":"","exif_camera_seo":"","exif_resolution":"","exif_sensitivity":"0","exif_exposure":"","exif_aperture":"","exif_focallength":"","is_downloadable":null,"is_notaccurate":null,"allow_fullsize":null}]

当然这是正确的,但如果我在$json = json_encode...下添加这2个新行,我会null

$newdata = array('test' => 'just testing');
$json[] = $newdata;

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

json_encode()返回一个字符串,因此您无法将其作为数组处理,即将元素添加到字符串中。

如评论中所述,您需要在json_encode()之前添加这些行,或使用json_decode()将其解码回数组,然后应用这些行然后返回json_encode()

json_encodejson_decode的使用示例:

$array = array("this" => array("will" => array("be" => "json")));
$string = json_encode($array); // string(31) "{"this":{"will":{"be":"json"}}}"

// ...

$array2 = json_decode($string); // now it’s same array as in first $array
$array2["new"] = "element";
$string2 = json_encode($array2);
var_dump($string2); // string(46) "{"this":{"will":{"be":"json"}},"new":"string"}"

答案 1 :(得分:0)

试试这个:

$newdata = array('test' => 'justtesting');
$results[] = $newdata;
$json = json_encode($results);

或者如果您在编码之后肯定需要它:

$json = json_encode($results);
//lots of stuff
$jarray = json_decode($results, true);
$newdata = array('test' => 'justtesting');
$jarray[] = $newdata;
$json = json_encode($jarray);