我是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