php – 将数组数据作为对象附加到json文件
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php – 将数组数据作为对象附加到json文件,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2646字,纯文字阅读大概需要4分钟。
内容图文
我有一个简单的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代码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);
}
逻辑是,将文件作为数组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
参考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);
}
编辑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);
}
?>
内容总结
以上是互联网集市为您收集整理的php – 将数组数据作为对象附加到json文件全部内容,希望文章能够帮你解决php – 将数组数据作为对象附加到json文件所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。