无法使用数字键解析 php 中的 JSON

Not able to parse JSON in php with numeric key

这是我的代码,但出现错误

Parse error: syntax error, unexpected '24' (T_LNUMBER), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in C:\xampp\htdocs\block_gecko\front\index.php on line 186

echo '<td style="font-size: 120%;">' .$character->24hour . '</td>';

PHP 变量不能以数字字符开头。试试这个:

$var = '24hour' ;
echo '<td style="font-size: 120%;">' .$character->$var . '</td>';

示例:

$json = json_decode('{"24hour":"test"}');
$key = "24hour";
echo $json->$key; // "test"

或者转换你的 JSON as array (json_decode($data, true)) 并使用 :

echo '<td style="font-size: 120%;">' .$character['24hour'] . '</td>';

另一种方式(感谢@mickmackusa):

$json = json_decode('{"24hour":"test"}');
var_dump($json->{'24hour'});