好吧,所以我对PHP,JSON等都很新。我得到了一个将HTML5表单输入到JSON数据库中的任务,并且还要记住该信息。
<?php
$f_name = $_POST['f_name'];
$l_name = $_POST['l_name'];
$u_email = $_POST['u_email'];
$u_adress = $_POST['u_adress'];
$u_postcode = $_POST['u_postcode'];
$u_place = $_POST['u_place'];
$u_birth = $_POST['u_birth'];
$file = file_get_contents("data.json");
$data = json_decode('data.json', true);
$last_item = end($data);
$last_item_id = $last_item['id'];
$data[] = array(
'f_name'=>$f_name,
'l_name'=>$l_name,
'u_email'=>$u_email,
'u_adress' =>$u_adress,
'u_postcode' =>$u_postcode,
'u_place'=>$u_place,
'u_birth'=>$u_birth,
'id' =>++$last_item_id
);
file_put_contents('data.json', json_encode($data));
?>
这是输出
[{"f_name":"Jack","l_name":"Smith","u_email":"jacksmith@hotmail.com","u_adress":"Something 1","u_postcode":"1111 AA","u_place":"SomeCity","u_birth":"jjjj-mm-dd","id":1}]
所以ID应该是自动增量但是当我尝试时我得到这个错误:
end() expects parameter 1 to be array, null given
指的是这部分
$last_item = end($data);
$last_item_id = $last_item['id'];
答案 0 :(得分:0)
如果你想得到这个是json数据的数组的最后一个值,你必须先使用json_decode。
$data = '[{"f_name":"Jack","l_name":"Smith","u_email":"jacksmith@hotmail.com","u_adress":"Something 1","u_postcode":"1111 AA","u_place":"SomeCity","u_birth":"jjjj-mm-dd","id":"1"}]';
因为当你解码它时,它仍然在一个数组下但只有一个索引,得到那个索引并试试这个:
$new_data = json_decode($data, true);
$last_item_id = end($new_data);
$id = $last_item_id = $last_item_id["id"];
$data = array(
'f_name'=>$f_name,
'l_name'=>$l_name,
'u_email'=>$u_email,
'u_adress' =>$u_adress,
'u_postcode' =>$u_postcode,
'u_place'=>$u_place,
'u_birth'=>$u_birth,
'id' => $id + 1
);
答案 1 :(得分:0)
替换此行:
$data = json_decode('data.json', true);
使用:
$data = json_decode($file, true);
并且无需再次提取id。删除:
$last_item_id = $last_item['id'];
使用last_item后:
$data = array(
'f_name'=>$f_name,
'l_name'=>$l_name,
'u_email'=>$u_email,
'u_adress' =>$u_adress,
'u_postcode' =>$u_postcode,
'u_place'=>$u_place,
'u_birth'=>$u_birth,
'id' =>++$last_item
);
请注意,如果您使用$data[] = array(....)
,则不会将数据保存在正确的json 1D阵列中
如果你想保留它,那么替换:
$last_item = end($data);
使用:
$last_item = end($data[0]);
长话短说,工作代码可以是:
$data = json_decode($file, true);
$last_item = end($data[0]);
$data[] = array(
'f_name'=>$f_name,
'l_name'=>$l_name,
'u_email'=>$u_email,
'u_adress' =>$u_adress,
'u_postcode' =>$u_postcode,
'u_place'=>$u_place,
'u_birth'=>$u_birth,
'id' =>++$last_item
);
OR
$data = json_decode($file, true);
$last_item = end($data);
$data = array(
'f_name'=>$f_name,
'l_name'=>$l_name,
'u_email'=>$u_email,
'u_adress' =>$u_adress,
'u_postcode' =>$u_postcode,
'u_place'=>$u_place,
'u_birth'=>$u_birth,
'id' =>++$last_item
);
取决于你想要的。 我希望它有所帮助