我有一个简单的JSON文件,每个JSON对象都包含一个直接的图像链接和文件夹名称:
[
{
"image": "http://placehold.it/350x150",
"folder": "Small"
},
{
"image": "http://placehold.it/450x250",
"folder": "Medium"
},
{
"image": "http://placehold.it/550x350",
"folder": "Medium"
}
]
我希望能够将来自post请求的两个值附加到一起,但结果是未更改的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);
}
逻辑是将文件解码为数组,合并新数组,然后编码结果并放回同一文件。我无法捕获任何错误。
$data = json_decode($file,true);
进行解码。 - bansi