Php JSON不是数组
我已经创建了一个类来处理我网站中的JSON操作。我试图在JSON文件中添加一个数组形式的事件标记,但是我得到一个错误,即array_值和array_push期望1个参数为数组。我不知道为什么会发生这种情况,因为变量被分配给数组。有什么建议吗?目前,JSON文件是空的Php JSON不是数组,php,arrays,json,Php,Arrays,Json,我已经创建了一个类来处理我网站中的JSON操作。我试图在JSON文件中添加一个数组形式的事件标记,但是我得到一个错误,即array_值和array_push期望1个参数为数组。我不知道为什么会发生这种情况,因为变量被分配给数组。有什么建议吗?目前,JSON文件是空的 class tagHandler { private $tagsFile = "tags.json"; private $LstTags; function __construct() {
class tagHandler {
private $tagsFile = "tags.json";
private $LstTags;
function __construct() {
$this->LstTags = array ();
if (! file_exists ($this->tagsFile)){
$fHND = fopen($this->tagsFile, "w");
$tmpArray = array(array("EID","EName","EColor", "EDel"));
fwrite($fHND, json_encode($tmpArray));
fclose($fHND);
}
$encodedInput = file ($this->tagsFile);
$this->LstTags = json_decode ($encodedInput[0]);
}
function __destruct(){
$this->update();
}
public function addTag($EName,$EColor){
$this->LstTags = array_values($this->LstTags);
array_push($this->LstTags, array($this->LstTags[count($this->LstTags)-1][0] + 1, $EName, $EColor, 0));
$this->update();
}
public function update(){
$this->LstTags = array_values($this->LstTags);
$fHND = fopen($this->tagsFile, "w");
fwrite($fHND, json_encode($this->LstTags));
fclose($fHND);
//empty memory region
$this->LstTags = array();
$encodedInput = file ( $this->tagsFile );
$this->LstTags = json_decode ( $encodedInput[0] );
}
}
电话:
错误:
[07-Feb-2017 22:14:33 Europe/London] PHP Warning: array_values() expects parameter 1 to be array, null given in /home/thomassm/public_html/functions/php/jsonclass.php on line 24
[07-Feb-2017 22:14:33 Europe/London] PHP Warning: array_push() expects parameter 1 to be array, null given in /home/thomassm/public_html/functions/php/jsonclass.php on line 25
[07-Feb-2017 22:14:33 Europe/London] PHP Warning: array_values() expects parameter 1 to be array, null given in /home/thomassm/public_html/functions/php/jsonclass.php on line 30
谢谢
您需要将true
作为第二个参数传递给,以便接收回数组
编辑:如果文件为空,因此,$encodedInput[0]
是空字符串,json\u decode
将返回null
。在以下情况下,可以返回空数组:
$this->LstTags = json_decode ($encodedInput[0], true) ?: [];
请删除文件并重试。它必须起作用 当然,还有
$this->LstTags = json_decode ($encodedInput[0], true);
if (!$this->LstTags) $this->LstTags = array();
最好用这个
file_put_contents($this->tagsFile, json_encode($this->LstTags));
编辑了答案,遗漏了该文件的存在,但为空。请解释否决票的原因-我遗漏了什么吗?你建议我将
文件放在哪里?内容放在哪里?在更新功能中?此外,当我从不同的位置调用该类时,JSON文件会出现在不同的目录中。我怎样才能解决这个问题?
$this->LstTags = json_decode ($encodedInput[0], true);
if (!$this->LstTags) $this->LstTags = array();
file_put_contents($this->tagsFile, json_encode($this->LstTags));