【发布时间】:2018-07-30 09:52:27
【问题描述】:
我有一个.json 文件,我想将一个对象附加到文件中的向量中,但出现了一些错误。
$json = file_get_contents('materialsdb/'.$_POST["materialtype"].'.json');
$jsonarray = json_decode($json, true);
$myObj->short = $_POST["short"];
//here I got: Warning: Creating default object from empty value
$myObj->title = $_POST["title"];
$myObj->description = $_POST["description"];
$myObj->cover = "";
$myObj->VR = false;
$myObj->slow = false;
$td = '2D';
$myObj->$td = false;
$fd = '3D';
$myObj->$fd = false;
if($_POST["isprivate"]){
$myObj->license = "nonfree";
} else {
$myObj->license = "free";
}
$myObj->lang = "en";
$id = count($jsonarray['packages'])+1;
$myObj->id = $id;
$myObj->soon = false;
$myObj->date = $_POST["date"];
$myObj->creator = $_POST["creator"];
$myObj->creator_institution = $_POST["creator_institution"];
$myObj->keywords = $_POST["keywords"];
$myObj->data = $_POST["data"];
$myJSON = json_encode($myObj);
echo $myJSON;
array_push($myJSON,$jsonarray['packages']);
//here I got: Warning: array_push() expects parameter 1 to be array, string given
$jsondata = json_encode($jsonarray, true);
$myFile = 'materialsdb/'.$_POST["materialtype"].'.json';
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
} else
echo "error";
当我尝试保存它时,它被保存了,但没有修改,没有新对象,但是我 echo $myJSON 那里的对象似乎不错。
这是我的.json 文件的示例:
{
"description": "some description",
"creators": [
{
"name": "cname",
"whoishe": "cv",
"avatar": "",
"id": 123
}
],
"lang": "en",
"materialname": "mat name",
"generalmaterialid": "mat_id",
"thismaterialid": "this_mat_id",
"packages": [
{
"short": "pack short desc",
"title": "pack title",
"description": "pack long desc",
"cover": "pack cover",
"VR": true,
"slow": true,
"2D": true,
"3D": true,
"license": "free",
"lang": "en",
"id": 1,
"soon": false
}
]
}
我的灵感来自这里:https://www.w3schools.com/js/js_json_php.asp 和这里http://www.kodecrash.com/javascript/read-write-json-file-using-php/。
我在这里做错了什么?我该如何解决?在这种情况下,正确的版本是什么?感谢您的帮助!
【问题讨论】:
-
php.net/manual/en/function.array-push.php - array_push 的第一个参数应该是你想要推送的数组。第二个参数应该是要推送的值。你只是把它们弄错了。这实际上是警告试图告诉您的内容。快速检查文档总是要付出代价的。
-
@ADyson 我怎样才能将此对象推送到
json?这不是一个数组,还是我错了? -
@ADyson 那么第一个警告呢?
-
那么您阅读我提供的链接了吗?您只需要将参数交换为 array_push。
array_push($jsonarray['packages'], $myJSON);文档非常清楚,您要将数据推送到其中的数组必须是函数中的 first 参数。 -
至于第一个警告,你知道你可以google一下警告和错误的文字吗?你很少是第一个遇到它的人。 google 上的第一个结果是stackoverflow.com/questions/8900701/…,你可以从那里得到一些重要的线索。如果我错了,请纠正我,但您似乎在这里遇到的主要问题是缺乏基础研究和阅读。