1

私はこの問題を 2 日間にわたって解決しようと試みてきましたが、うまくいきませんでした。PHPを使用して、サーバー上の.jsonファイルに保存されているjson配列に結合/追加しようとしています。

これは、私が結合しようとしているものの短いバージョンです。

box.json:

[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"}]

投稿されたjson:

[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]

これが必要です。

[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]

これは私が得るものです。(配列内の配列)

[{"date":"25.4.2013 10:40:10"},{"comment":"some text"},{"comment":"some more text"},
[{"date":"25.4.2013 10:45:15"},{"comment":"another quote"},{"comment":"quote"}]]

これは私のコードです:

<?php
$sentArray = $_POST['json'];
$boxArray = file_get_contents('ajax/box.json');
$sentdata = json_decode($sentArray);
$getdata = json_decode($boxArray);
$sentdata[] = $getdata;   /* I also tried array_push($sentdata, $getdata); */
$json = json_encode($sentdata);
$fsize = filesize('ajax/box.json');
if ($fsize <= 5000){
    if (json_encode($json) != null) { /* sanity check */
    $file = fopen('ajax/box.json' ,'w+');
    fwrite($file, $json);
    fclose($file);
}else{
    /*rest of code*/
}
?>

私の正気が疑問視され始めているのを助けてください。

4

3 に答える 3

0

これの代わりに:

$sentdata[] = $getdata;   /* I also tried array_push($sentdata, $getdata); */

試す:

$combinedData = array_merge($sentData, $getData);
$json = json_encode($combinedData);

array_mergeを使用すると、1 つの配列を値として別の配列に追加するのではなく、配列を 1 つに結合できます。

結果のデータの名前を変更したことに注意してください-同じ名前で大文字が異なる変数を避けるようにしてください。これにより、物事が理解しやすくなります(あなたとあなたのコードをサポートする将来の開発者にとって)。

乾杯

于 2013-04-25T19:17:50.240 に答える