Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Array_push在JSON文件中给出空值_Php_Json - Fatal编程技术网

Php Array_push在JSON文件中给出空值

Php Array_push在JSON文件中给出空值,php,json,Php,Json,我想用HTML表单将数组添加到现有的.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, $

我想用HTML表单将数组添加到
现有的.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为数组,空值在…”


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

json\u decode()
添加第二个参数,并将其设置为
true
:-

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

除了使用另一个答案中已经提到的关联版本的
json_decode
,我认为问题在于您的输入json文件

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

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

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

$tempArray=json_decode($fileTmp,true);array_push($tempArray,$newArray)试试看,这个错误是否也发生在提供的json文件中,还是仅在以空文件开始时才发生?@Anant哦,是的,谢谢!我没看见。。。aghidini问题已解决,但已提供json@PatrickDully很高兴为您提供帮助。:)事实上,他显示的json是有效的,但这段代码对于防止错误也很有用。so+1。@Anant我同意他的输入json是有效的,但我怀疑他只是在开始时收到错误,即输入json为空(或不存在)。我认为
json\u decode
应该生成一个有效的数组,第二个参数也是
false
,它应该只生成一个对象数组,但是OP错误是关于第一个参数(即数组)。当你试图将数组推入一个对象数组时,你也会得到这个错误(我认为)@Anant实际上可以工作(尽管最终的数组包含对象和新添加的数组):它甚至可以生成一个有效的json输出: