动态将数组推入多维数组

时间:2018-06-30 21:14:28

标签: php arrays

我正在尝试为Facebook Messenger SDK动态构建一个数组,并使用数据库中的数据填充它。

无论尝试如何,我似乎都无法获得结构正确的数组。

我需要什么:

        $messages = [
            "attachment" => [
                "type" => "template",
                "payload" => [
                    "template_type" => "generic",
                    "elements" => [[
                        "title" => $row['title'],
                        "item_url" => $row['item_url'],
                        "image_url" => $row['image_url'],
                        "subtitle" => $row['subtitle'],
                        "buttons" => [[
                        "type" => "web_url",
                        "url" => "www.google.com",
                        "title" => "View Website"],
                        ["type" => "postback",
                            "title" => "Start Chatting",
                            "payload" => "start"]]
                    ]
                ]]
            ]];

我需要根据数据库中的内容在buttons中创建数据,并尝试使用array_merge并将数组作为字符串插入:

        // Created arrays
        if (!empty($row['button1_type'])) {
            $buttons[] = array("type" => $row['button1_type'],"url" => $row['button1_url'],
                "title" => $row['button1_title'],
                "payload" => $row['button1_payload']);
        }
        if (!empty($row['button2_type'])) {
            $buttons[] = array("type" => $row['button2_type'],"url" => $row['button2_url'],
                "title" => $row['button2_title'],
                "payload" => $row['button2_payload']);
        }

        // In the case when I had array_merge - $buttons were actually named as $buttons1 and $buttons2
        $buttons = array_merge($buttons1, $buttons2);

        // Tried to add it as a string
        if (!empty($row['button2_type'])) {
            $buttons = "\"type\" => ".$row['button2_type'].",\"url\" => .".$row['button2_url'].",
                \"title\" => ".$row['button2_title'].",
                \"payload\" => ".$row['button2_payload'];
        }

        $messages = [
            "attachment" => [
                "type" => "template",
                "payload" => [
                    "template_type" => "generic",
                    "elements" => [[
                        "title" => $row['title'],
                        "item_url" => $row['item_url'],
                        "image_url" => $row['image_url'],
                        "subtitle" => $row['subtitle'],
                        "buttons" => [
                            $buttons
                        ]
                    ]
                ]]
            ]];

该屏幕截图显示了正确与错误之间的区别: enter image description here

所以基本上$buttons是在一个额外的数组中创建的,我该如何摆脱它?也许我应该改变整个方法?

1 个答案:

答案 0 :(得分:1)

使用

"buttons" => [$buttons]
//new array  ^        ^  

正在创建一个带有方括号的新数组,以避免出现这种情况。使用

"buttons" => $buttons