如何使用php向数组json添加新数据?
我有4个输入,由Ajax 4数据发送到php文件: 如何加载json文件,然后使用php添加新数据如何使用php向数组json添加新数据?,php,jquery,json,file,Php,Jquery,Json,File,我有4个输入,由Ajax 4数据发送到php文件: 如何加载json文件,然后使用php添加新数据 <input type="text" id="name"> <input type="text" id="surname"> <input type="text" id="mobile"> <input type="text" id="email"> <script> var name = $("#name").val(); var su
<input type="text" id="name">
<input type="text" id="surname">
<input type="text" id="mobile">
<input type="text" id="email">
<script>
var name = $("#name").val();
var surname = $("#surname").val();
var mobile = $("#mobile").val();
var email = $("#email").val();
$.ajax({type:"POST",
url:"fill.php",
data:"name="+nombre+"&surname="+surname+"&mobile="+mobile+"&email="+email,
success:function(data) {
这里我有一个错误fill.php文件:
<?php
$name = $_POST['name'];
$surname =$_POST['surname'];
$mobile = $_POST['mobile'];
$email =$_POST['email'];
$file = 'people.json';
$data = json_decode(file_get_contents($file));
$newdata = array('name'=>$name, 'surname' => $surname, 'mobile'=>$mobile,'email'=>$email);
$data[] = $newdata;
file_put_contents($file, json_encode($data));
?>
当我执行它时,它会删除所有的people.json日期,每次我添加新数据时,它都会给我下一个结果:[{},{},{},{},{}]json decode接受第二个参数,设置它,得到的是数组而不是stdClass对象。你需要向json_decode添加一个secnod参数,这样它就变成了一个数组,试试这个
<?php
$name = $_POST['name'];
$surname =$_POST['surname'];
$mobile = $_POST['mobile'];
$email =$_POST['email'];
$file = 'people.json';
$data = json_decode(file_get_contents($file),1);
$newdata = array('name'=>$name, 'surname' => $surname, 'mobile'=>$mobile,'email'=>$email);
$data[] = $newdata;
file_put_contents($file, json_encode($data));
?>
第一次,当你使用它时,它工作正常??关于这个json文件,你已经有好几篇帖子了。为什么不更改文件中的数据结构,使其与页面中所需的内容相匹配,而不必将浏览器中的数据映射到其他格式。然后您将在javascript和phpyeah中使用相同的结构,但是当我填写表单时,它会删除所有的人。json datatryjson\u decode(file\u get\u contents($file),true)代码>无论发生什么情况,这都应该返回一个数组。@dualed是的,你说得对,现在可以了json_decode(file_get_contents($file),true)和son_decode(file_get_contents($file),1)之间有什么区别;,是相同的吗?@Kakitori 1和true做相同的事情,与0和false做相同:)@Kakitori作为旁注,您的JSON数组应该从0开始,而不是从1开始:)只是一个提示您的意思是什么??我必须将json解码(文件获取内容($file),1)更改为json解码(文件获取内容($file),0)??
<?php
$name = $_POST['name'];
$surname =$_POST['surname'];
$mobile = $_POST['mobile'];
$email =$_POST['email'];
$file = 'people.json';
$data = json_decode(file_get_contents($file),1);
$newdata = array('name'=>$name, 'surname' => $surname, 'mobile'=>$mobile,'email'=>$email);
$data[] = $newdata;
file_put_contents($file, json_encode($data));
?>