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

使用PHP解码JSON字符串并创建一个变量,php,json,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;

我有以下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;

}
那么如何设置电子邮件和密码的变量呢

没有必要使用foreach


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

$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'];

}

这会更好,因为您正在查看所有输入,每次都会收到其电子邮件和密码。

$email=$input['email']尝试打印\u r$input以查看解码数据的结构。从JSON的结构来看,这应该非常明显,但如果阅读JSON对您没有帮助,请尝试这种方式。@JonStirling奇妙!谢谢:可能的副本
$content = file_get_contents("php://input");
$inputs = json_decode($content, true);


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

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

}