我基本上知道如何通过PHP向JSON添加新的键值对,如:
$json->newObject = "value";
但我无法弄清楚如何给出该对的密钥,一个随机ID。
我尝试过类似的事情:
$id = rand(99, 9999);
$json["newObject" . $id] = "value";
错误为:Fatal error: Cannot use object of type stdClass as array in /home/methodjs/public_html/projects/chat/send.php on line 8
和
$id = rand(99, 9999);
$json->("newObject" . $id) = "value";
错误为:Parse error: syntax error, unexpected '(', expecting T_STRING or T_VARIABLE or '{' or '$' in /home/methodjs/public_html/projects/chat/send.php on line 8
我希望必须有一些简单的方法来做到这一点。谢谢你的帮助。
答案 0 :(得分:1)
答案 1 :(得分:1)
您可以使用
$json = "{}";
$json = json_decode($json);
$json->newObject = "value";
$id = rand(99, 9999);
$json->{"newObject" . $id} = "value";
$json->array = array(mt_rand(),mt_rand());
print_r($json);
输出
stdClass Object
(
[newObject] => value
[newObject1764] => value
[array] => Array
(
[0] => 1176886102
[1] => 1306108513
)
)