[英]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.