我有具有每JSON对象的直接图像链接和文件夹名称简单的JSON文件:追加阵列数据作为对象来JSON文件
[
{
"image": "http://placehold.it/350x150",
"folder": "Small"
},
{
"image": "http://placehold.it/450x250",
"folder": "Medium"
},
{
"image": "http://placehold.it/550x350",
"folder": "Medium"
}
]
我想这两个值从后追加,但结果是一个不变的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该文件作为一个阵列,所述新的数组,并到的是,然后将结果进行编码并投入相同的文件。我一直无法捕捉任何类型的错误。
尝试'$ data = json_decode($ file,true);' – bansi
我以为我已经这样做了,以确保它作为一个数组返回,但我偶然在文件中添加了bool参数。但仍然没有改变。 – benbob
file_put_contents('./images_list。json',json_encode($ result)); –