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

时间:2016-04-10 07:26:33

标签: php arrays

我有一个数组:

$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

我很蠢。谢谢你的帮助。

2 个答案:

答案 0 :(得分:1)

试试这个:

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

希望这有帮助。

答案 1 :(得分:1)

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

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