在PHP中将键值附加到关联数组


Append Key Value to Associative Array in PHP

我有一个数组:

$data["messages"][] = array("chatId" => $chat_id, "type" => "text", "to" => $username, "body" => "success");

当打印数组时,它看起来像这样:

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 ) ) ) ) ) )

注意新的键值"keywords"=>数组(…在上一个数组关闭后添加。我希望它看起来像:

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

我很笨。谢谢你的帮助。

您正试图将$arr_keyboards数组添加到$data["messages"]数组的第一个元素中
更改"关键"代码行如下:

$data["messages"][0]["keyboards"] = $arr_keyboards;

试试这个:

$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);

希望这能有所帮助。