如何用php向数组json添加新数据?

时间:2013-01-27 00:44:22

标签: php jquery json file

我有4个输入,由Ajax 4数据发送到php文件: 如何加载json文件,然后添加新的数据?

<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) {

} }); JSON文件:(people.json)

{
"1":
{
    "Name" : "Jhon",
    "Surname" : "Kenneth",
    "mobile" : 329129293,
    "email" : "jhon@gmail.com"
},
"2":
{
    "Name" : "Thor",
    "Surname" : "zvalk",
    "mobile" : 349229293,
    "email" : "thor@gmail.com"
}
}

这里我有一个错误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日期,每次我添加新数据时,它都会给我下一个结果:[{},{},{},{}]

2 个答案:

答案 0 :(得分:1)

你需要向json_decode添加第二个参数,使它成为一个数组,试试这个

<?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));
?>

答案 1 :(得分:0)

json decode接受第二个参数,设置它并获得数组而不是stdClass对象。