doukengsha9472 2013-06-06 21:54
浏览 48
已采纳

向JSON添加新行

I have successfully get content from the database and output the results in JSON. But I want to add a text that doesn't exists in the database and it's here I'm stuck.

$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;

That code gives me

[{"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}]

Which is correct of course but if I add these 2 new lines under $json = json_encode... I'm getting null.

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

What have I done wrong here?

  • 写回答

2条回答 默认 最新

  • dousha7904 2013-06-06 21:58
    关注

    json_encode() returns a string, so you can’t handle it as an array, i.e. add elements to string.

    As noted in comments, you need to add those lines before json_encode() or decode it back to array using json_decode(), then apply the lines and then back json_encode().

    Example about usage of json_encode and json_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条)

报告相同问题?

悬赏问题

  • ¥15 Pwm双极模式H桥驱动控制电机
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题