直接の画像リンクと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 し、新しい配列をそれにマージし、結果をエンコードして同じファイルに入れるのは簡単であるべきだということです。どのようなエラーもキャプチャできませんでした。