PHP Echo显示完整的JSON行数据,而不仅仅是我需要的


PHP Echo shows full JSON line data not only what i required

最近我在JQuery中使用了一些JSON数据。现在我想在PHP同样的事情。例如:

MySQL查询返回类似

的数据
$result='{"username":"john","age":"18", "birthdate":"19880221"}';

但是当我在PHP中回显这些数据时,比如:

echo $result.username;
echo $result.age;

显示输出:

{"username":"john","age":"18", "birthdate":"19880221"}.username
{"username":"john","age":"18", "birthdate":"19880221"}.age

但是我想输出这个:

John
18

PHP不是Javascript, .运算符用于字符串连接,PHP没有本机对JSON语法的支持。您需要将JSON格式的数据转换为数组,并使用数组语法:

$result = json_decode($result, true);
echo $result['username'];
echo $result['age'];

php不是js。您必须先解码数据,使用json_decode

如果$result 真的包含您发布的数据

您的结果实际上只是一个字符串,格式类似JSON。它不是PHP中的数组。如果想处理JSON输出,可以先使用json_decode(),然后通过PHP数组语法访问数据,如下所示:

$result = json_decode($result,true);
echo $result['some_key'];