[英]Append Key Value to Associative Array in PHP
I have an array: 我有一个数组:
$data["messages"][] = array("chatId" => $chat_id, "type" => "text", "to" => $username, "body" => "success");
When print_r the array it looks like this: 当print_r数组时,它看起来像这样:
Array ( [messages] => Array ( [0] => Array ( [chatId] => d3a611401de00e8c8b3e225a7cf95484033f57ea18c442249ee9b5bcb63c9a96 [type] => text [to] => pitashi [body] => success ) ) )
But when I try to append the new key value to the end like this: 但是,当我尝试将新的键值附加到末尾时,如下所示:
$arr_keyboards[] = array(
"type" => "suggested",
"responses" => array(
array("type" => "text", "body" => "Yes"),
array("type" => "text", "body" => "No")
)
);
$data["messages"]["keyboards"] = $arr_keyboards;
I end up with this: 我最终得出以下结论:
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 ) ) ) ) ) )
Notice the new key value "keyboards" => array(... gets added AFTER the previous array gets closed. What I want it to look like is: 注意新的键值“ 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 ) ) ) ) )
In the end I'm json encoding it. 最后,我对它进行json编码。 Here is a screenshot of how it looks and where I need it to be https://www.evernote.com/l/AETNv5OhBI1HtLzqXalq-BCfOIwz4U0jlWw and here is a screenshot of ultimately how I want it to look https://www.evernote.com/l/AETRjOREKvBHLpXyh3NdZdGAryyxO2rIiwg
这是它的外观屏幕截图,以及我需要在哪里使用的屏幕截图https://www.evernote.com/l/AETNv5OhBI1HtLzqXalq-BCfOIwz4U0jlWw ,这是最终我希望它的外观屏幕截图https://www.evernote .com / l / AETRjOREKvBHLpXyh3NdZdGAryyxO2rIiwg
I'm dumb. 我很笨 Thanks for the help.
谢谢您的帮助。
Try this: 尝试这个:
$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);
Hope this helps. 希望这可以帮助。
You are trying to add the $arr_keyboards
array into the first element of the $data["messages"]
array. 您试图将
$arr_keyboards
数组添加到$data["messages"]
数组的第一个元素中。
Change the " crucial " line of code as following: 更改“ 关键 ”代码行,如下所示:
$data["messages"][0]["keyboards"] = $arr_keyboards;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.