我是PHP的新手,我认为我的代码正在工作,但似乎存在一些小问题。只有当输入为0时,PHP才能访问空元素
这是我的代码:
<?php
$string = file_get_contents("jsontest.txt");
$result = json_decode($string);
if(isset($_POST['value']) && !empty($_POST['value']) &&
isset($_POST['whatElement']) && !empty($_POST['whatElement']) &&
isset($_POST['category']) && !empty($_POST['category']) &&
isset($_POST['model']) && !empty($_POST['model'])) {
$value = $_POST['value'];
$whatElement = $_POST['whatElement'];
$category = $_POST['category'];
$model = $_POST['model'];
}
$result->$category->$model->$whatElement = $value;
echo $result->$category->$model->$whatElement;
$myfile = fopen("jsontest.txt", "w") or die("Unable to open file!");
$txt = json_encode($result);
fwrite($myfile, $txt);
?>
我用这个作为一个HTML输入标签的响应。如果是相关的。这是我用来调用我的PHP脚本
function handleEnter(value, type, exactModel)
{
var bothParts = exactModel.split("_");
category = bothParts[0];
model = bothParts[1];
$.ajax({
url: "morework.php",
data: {value: value, whatElement: type, category: category, model: model},
type: 'post',
success: function(ret){
//location.reload();
console.log(ret);
}
})
}
这传递了正确的数据到PHP脚本,但在“值”变量被设置为0,我得到以下的JavaScript代码:“致命错误:在无法访问空属性...”
我试图改变代码如下:
相反的:$result->$category->$model->$whatElement = $value;
我把:$result->category->model->whatElement = $value;
这似乎处理错误,但根本不会更改json文件。而如果我有原始它不适用于0,但确实更改所有其他数字的JSON文件。
我已经在$ _POST上使用了var_dump,并且在所有情况下这似乎都保持了正确的值。然而,如果我在0发送,如果我回声这一行:echo "$value $whatElement $category $model";
它显示为空的,而它被填充时的var_dump为0值测试的非零
实施例:
array(4) {
["value"]=>
string(1) "0"
["whatElement"]=>
string(8) "Borrowed"
["category"]=>
string(9) "Category"
["model"]=>
string(8) "Model"
}
的关于如何解决这个问题的意见/建议非常感谢。
[为什么要同时检查isset()函数和!空() ](https://stackoverflow.com/q/4559925/476) – deceze
这个答案意味着使用!empty()会导致不需要的结果吗?或者它是有目的的吗?在你所链接的帖子的回答中,似乎有矛盾的观点。 – Abdall
'empty'的用途是和'== false' *做相同的检查,如果你检查的变量没有设置,就不会抛出任何错误。*就是这样。没有更多,没有更多。 – deceze