[英]Append Key Value to Associative Array in PHP
我有一个数组:
$data["messages"][] = array("chatId" => $chat_id, "type" => "text", "to" => $username, "body" => "success");
当print_r数组时,它看起来像这样:
Array ( [messages] => Array ( [0] => Array ( [chatId] => d3a611401de00e8c8b3e225a7cf95484033f57ea18c442249ee9b5bcb63c9a96 [type] => text [to] => pitashi [body] => success ) ) )
但是,当我尝试将新的键值附加到末尾时,如下所示:
$arr_keyboards[] = array(
"type" => "suggested",
"responses" => array(
array("type" => "text", "body" => "Yes"),
array("type" => "text", "body" => "No")
)
);
$data["messages"]["keyboards"] = $arr_keyboards;
我最终得出以下结论:
Array ( [messages] => Array ( [0] => Array ( [chatId] => d3a611401de00e8c8b3e225a7cf95484033f57ea18c442249ee9b5bcb63c9a96 [type] => text [to] => pitashi [body] => success ) [keyboards] => Array ( [0] => Array ( [type] => suggested [responses] => Array ( [0] => Array ( [type] => text [body] => Yes ) [1] => Array ( [type] => text [body] => No ) ) ) ) ) )
注意新的键值“ keyboards” => array(...在上一个数组关闭后被添加。我希望它看起来像是:
Array ( [messages] => Array ( [0] => Array ( [chatId] => d3a611401de00e8c8b3e225a7cf95484033f57ea18c442249ee9b5bcb63c9a96 [type] => text [to] => pitashi [body] => success [keyboards] => Array ( [0] => Array ( [type] => suggested [responses] => Array ( [0] => Array ( [type] => text [body] => Yes ) [1] => Array ( [type] => text [body] => No ) ) ) ) )
最后,我对它进行json编码。 这是它的外观屏幕截图,以及我需要在哪里使用的屏幕截图https://www.evernote.com/l/AETNv5OhBI1HtLzqXalq-BCfOIwz4U0jlWw ,这是最终我希望它的外观屏幕截图https://www.evernote .com / l / AETRjOREKvBHLpXyh3NdZdGAryyxO2rIiwg
我很笨 谢谢您的帮助。
尝试这个:
$data["messages"][] = array(
"chatId" => $chat_id,
"type" => "text",
"to" => $username,
"body" => "success"
);
$arr_keyboards = array(
"type" => "suggested",
"responses" => array(
array("type" => "text", "body" => "Yes"),
array("type" => "text", "body" => "No")
)
);
foreach ($data["messages"] as $message) {
$message["keyboards"] = $arr_keyboards;
}
echo json_encode($message);
希望这可以帮助。
您试图将$arr_keyboards
数组添加到$data["messages"]
数组的第一个元素中。
更改“ 关键 ”代码行,如下所示:
$data["messages"][0]["keyboards"] = $arr_keyboards;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.