Array_push在JSON文件中给出null

时间:2017-02-25 13:59:44

标签: php json

我想将数组添加到带有HTML表单的existing .json文件中。

这是我的PHP:

$myFile = "data.json";      
$newArray = array(
    'name'=> $_POST['name'],
    'date'=> $_POST['date']
);

$fileTmp = file_get_contents($myFile);
$tempArray = json_decode($fileTmp);
array_push($tempArray, $newArray);
$jsonData = json_encode($tempArray);
file_put_contents($myFile, $jsonData);

这是我的JSON:

[
  {
    "name": "name 1",
    "date": "01.02.2017"
  },
  {
    "name": "name 2",
    "date": "05.02.2017"
  },
  {
    "name": "name 3",
    "date": "05.03.2017"
  }
]

问题是我收到了警告

  

" array_push()期望参数1为数组,在......"

中给出null

并且在JSON中只有null。我的代码有什么问题?

3 个答案:

答案 0 :(得分:2)

json_decode()添加第二个参数并将其设置为true: -

$tempArray = json_decode($fileTmp,true); 
array_push($tempArray, $newArray);

答案 1 :(得分:1)

除了使用另一个答案中已经说明的json_decode的关联版本之外,我认为问题是你输入的json文件。

如果json为空,您应检查有效内容并创建默认数组:

$fileTmp = file_get_contents($myFile);
$tempArray = json_decode($fileTmp, true);
if (!$tempArray) {
    $tempArray = array();
}
...

答案 2 :(得分:-1)

我遵守了代码,它有效。检查data.json文件的权限。

相关问题