我有一个简单的json文件,它有一个直接的图像链接和每个json对象的文件夹名称:
[
{
"image": "http://placehold.it/350x150",
"folder": "Small"
},
{
"image": "http://placehold.it/450x250",
"folder": "Medium"
},
{
"image": "http://placehold.it/550x350",
"folder": "Medium"
}
]
Run Code Online (Sandbox Code Playgroud)
我想从帖子中追加这两个值,但结果是一个未更改的json文件.这是PHP代码w/comments:
$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);
}
Run Code Online (Sandbox Code Playgroud)
逻辑是,将文件作为数组json_decode编码应该很简单,将新数组合并到该数组上,然后对结果进行编码并放入同一文件中.我也无法捕捉到任何错误.
$data = json_decode($file, true);
//When TRUE, returned objects will be converted into associative arrays.
unset($file);
$newImage = array('image' => $link, 'folder' => $category);
//$newImage['image'] = $link;
//$newImage['folder'] = $category;
$result = array_merge($data, $newImage);
//don't need to cast
Run Code Online (Sandbox Code Playgroud)
参考PHP json_decode手册
编辑以下代码工作(测试)
function addToJsonImageList($link, $category) {
$file = file_get_contents('./images_list.json', true);
$data = json_decode($file,true);
unset($file);
//you need to add new data as next index of data.
$data[] = array('image' => $link, 'folder' => $category);
$result=json_encode($data);
file_put_contents('./images_list.json', $result);
unset($result);
}
Run Code Online (Sandbox Code Playgroud)
编辑2添加了大量的错误报告和调试.请让我知道以下内容的输出.下面的代码未经过测试(只需输入此处).如果发现任何语法错误,请修复.在这里已经很晚了,明天只能查看我的时间,但可以回复.
<?php
//display all errors and warnings
error_reporting(-1);
addToJsonImageList('test link', 'test category');
function addToJsonImageList($link, $category) {
$file = file_get_contents('./images_list.json', true);
if ($file===false)die('unable to read file');
$data = json_decode($file,true);
if ($data ===NULL)die('Unable to decode');
unset($file);
echo "data before\n";
var_dump ($data);
//you need to add new data as next index of data.
$data[] = array('image' => $link, 'folder' => $category);
echo "data after\n";
var_dump ($data);
$result=json_encode($data);
if (file_put_contents('./images_list.json', $result) === false){
die('unable to write file');
}
unset($result);
}
?>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14422 次 |
| 最近记录: |