3

直接の画像リンクとjsonオブジェクトごとのフォルダー名を持つ単純なjsonファイルがあります。

[
        {
                "image": "http://placehold.it/350x150",
                "folder": "Small"
        },
        {
                "image": "http://placehold.it/450x250",
                "folder": "Medium"
        },
        {
                "image": "http://placehold.it/550x350",
                "folder": "Medium"
        }
]

投稿からこれら 2 つの値を追加したいのですが、結果は変更されていない json ファイルです。コメント付きのPHPコードは次のとおりです。

$directLink = $_POST['txtDirectLink'];
$category = $_POST['selectCategoriesImages'];
$util->addToJsonImageList($directLink, $category);

//decodes the json image list, merges to the decoded array a new image, then encodes back to a json file
function addToJsonImageList($link, $category) {
    $file = file_get_contents('./images_list.json', true);
    $data = json_decode($file);
    unset($file);

    $newImage = array('image' => $link, 'folder' => $category);
    //$newImage['image'] = $link;
    //$newImage['folder'] = $category;
    $result = array_merge((array)$data, (array)$newImage);

    json_encode($result);
    file_put_contents('./images_list.json', $result);
    unset($result);
}

ロジックは、ファイルを配列として json_decode し、新しい配列をそれにマージし、結果をエンコードして同じファイルに入れるのは簡単であるべきだということです。どのようなエラーもキャプチャできませんでした。

4

4 に答える 4

0

あなたの問題は、次のコード行にあります

json_encode($result);
file_put_contents('./images_list.json', $result);

あなたの結果をキャプチャしていないjson_encodeので、ファイルに書き込みarrayます。

次のように読むようにコードを調整する必要があります

$result = json_encode($result);
file_put_contents('./images_list.json', $result);
于 2013-08-19T05:57:41.347 に答える