我的JSON数据如下所示:
[
{
"email":"test@test.com",
"firstName":"test",
"lastName":"test",
"value":"test@test.com",
"tokens":"test@test.com"
},
{
...
}
]
和用于创建json文件的php数据如下所示:
<?php
session_start();
include('connection.php');
$userId = $_SESSION['sess_user_id'];
$act = $_POST['action'];
$sth = mysql_query("SELECT email, firstName, lastName, email AS value, email AS tokens FROM User");
$rows = array();
while($r = mysql_fetch_assoc($sth))
{
$rows[] = $r;
}
$fp = fopen('./test.json', 'w');
fwrite($fp, json_encode($rows));
fclose($fp);
?>
当用户被添加到数据库时,它运行这个PHP代码:
$file = './test.json';
$data = json_decode(file_get_contents($file), true);
$newdata = array('email'=>$email, 'firstName' => $firstName, 'lastName'=>$lastName, 'value'=>$email, 'tokens'=>$email);
$data[] = $newdata;
file_put_contents($file, json_encode($data));
我希望我的JSON文件看起来像这样:
[
{
"email":"test@test.com",
"firstName":"test",
"lastName":"test",
"value":"test@test.com",
"tokens":[
"test@test.com"
]
}
]
我试图解决这个问题,但我做不到。请帮帮忙?
答案 0 :(得分:2)
php处理与javascript不同的数组(区分对象和数组)。
$newdata = array(
'email'=>$email,
'firstName' => $firstName,
'lastName'=>$lastName,
'value'=>$email,
'tokens'=>array($email)
);
应该这样做。