0

データベースからコンテンツを正常に取得し、結果を 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}]

もちろんこれは正しいですが、これらの 2 つの新しい行を下に追加すると$json = json_encode...null.

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

ここで私は何を間違えましたか?

4

2 に答える 2

0

json_encode()文字列を返すため、配列として扱うことはできません。つまり、文字列に要素を追加します。

コメントに記載されているように、前にこれらの行を追加するjson_encode()か、 を使用して配列にデコードしてからjson_decode()、行を適用してから戻す必要がありますjson_encode()

json_encodeとの使用例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"}"
于 2013-06-06T21:58:40.997 に答える