使用PHP解码JSON字符串并创建变量

时间:2017-03-23 09:35:02

标签: php json

我有以下JSON字符串:

{ email: "test@test.de", password: "123456" }

在我的PHP文件中,我使用以下代码:

$content = file_get_contents("php://input");
$input = json_decode($content, true);


foreach ($input as $value) {
    $names[] = $value;

    $email = $value->email;
    $password = $value->password;

}

那么如何为电子邮件和密码设置变量?

2 个答案:

答案 0 :(得分:0)

PHP code demo

不需要foreach

$content = '{ "email": "test@test.de", "password": "123456" }';
$input = json_decode($content,true);


$email = $input["email"];
$password = $input["password"];

print_r($email);  //test@test.de
print_r($password); //123456

答案 1 :(得分:0)

您可以通过以下方式引用它:

$content = file_get_contents("php://input");
$input = json_decode($content, true);


foreach ($input as $value) {
    $names[] = $value;

    $email = $value['email'];
    $password = $value['password'];

}

只是一个建议,请尽量确保您的变量名称有意义,以便它可以帮助您了解更多如何访问它。例如,如果以这种方式使用它会更好:

$content = file_get_contents("php://input");
$inputs = json_decode($content, true);


foreach ($inputs as $input) {
    $names[] = $input;

    $email = $input['email'];
    $password = $input['password'];

}

这样做更好,因为您正在浏览所有输入,并且每个输入都会收到其电子邮件和密码。