我想将数据导出到json文件。这将是一个简单的注册页面。 我有数据,但我无法导出它们,因为我有3个参数:
-Username -电子邮件 -Password
<html>
<body marginleft="auto" marginright="auto" marginwidth="500px" >
<form method="post">
Username:
<input type="text" name="username" placeholder="Username">
<br>
Email:
<input type="text" name="email" placeholder="Email">
<br>
Password:
<input type="text" name="password" placeholder="Password">
<br>
<?php
$allDatas = json_decode(file_get_contents('data.json'), true);
$usernames = array();
$passwords = array();
$emails = array();
foreach ($allDatas as $data) {
array_push($usernames, $data[0]);
}
foreach ($allDatas as $data) {
array_push($passwords, $data[1]);
}
foreach ($allDatas as $data) {
array_push($emails, $data[2]);
}
if (isset($_POST['email']) && isset($_POST['password']) && isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$foundedUser = false;
foreach ($usernames as $key => $value) {
if ($value == $username) {
echo "Error: Username exsists;";
}
}
foreach ($emails as $key => $value) {
if ($value == $email) {
echo "Error: Email registered;";
}
}
array_push($usernames, $username);
array_push($passwords, $password);
array_push($emails, $email);
unset($allDatas);
$allDatas = array();
????
}
}
?>
<input type="submit" value="Registration">
<br>
</body>
</html>
感谢您的回答!
答案 0 :(得分:1)
无需创建单独的$usernames
,$emails
和$passwords
数组。您只需循环浏览$allData
即可搜索与注册匹配的现有条目。
其次,您需要在找到匹配项时设置$founduser
,并在添加新用户之前进行检查。
第三,您应该将新用户添加到$allData
,然后将其作为JSON写入文件。
<?php
if (isset($_POST['email']) && isset($_POST['password']) && isset($_POST['username'])) {
$allDatas = json_decode(file_get_contents('data.json'), true);
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$foundedUser = false;
foreach ($allDatas as $value) {
if ($value[0] == $username) {
echo "Error: Username exsists;";
$foundUser = true;
break;
} elseif ($value[2] == $email) {
echo "Error: Email registered;";
$foundUser = true;
break;
}
}
if (!$foundUser) {
$allDatas[] = array($username, $email, $password);
file_put_contents('data.json', json_encode($allDatas));
}
unset($allDatas);
}
}
?>
答案 1 :(得分:0)
所以你想要从$ usernames,$ passwords和$ emails这些数组创建一个json字符串。您需要创建一个新数组并将这些数组插入到该新数组中,之后只需使用json_encode
,您将获得一个新的json字符串。
在if条件之外,你必须这样做。
你有这些:
array_push($usernames, $username);
array_push($passwords, $password);
array_push($emails, $email);
这样做:
$newArr = array();
$newArr[] = $username;
$newArr[] = $passwords;
$newArr[] = $emails;
$newstring = json_encode($newArr);
让我知道你是否有帮助。