如何使用 PHP 将新数据添加到数组 JSON 中


how add new data to array json with php?

我有 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"
}
}

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

{},{},{},{},{}]

你需要添加一个secnod参数到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));
?>

json 解码接受第二个参数,设置它,你会得到数组而不是 stdClass 对象。