A
A
AleDv2019-06-14 10:04:10
PHP
AleDv, 2019-06-14 10:04:10

How to convert an associative array in PHP to a JSON array?

Hello. There is a task to generate a JSON keyboard object for a bot in VK. The structure is as follows:

{ 
    "one_time": false, 
    "buttons": [
        [{ 
                "action": { 
                    "type": "text", 
                    "payload": "{\"button\": \"1\"}", 
                    "label": "Negative" 
                }, 
                "color": "negative" 
            }, 
            { 
                "action": { 
                    "type": "text", 
                    "payload": "{\"button\": \"2\"}", 
                    "label": "Positive" 
                }, 
                "color": "positive" 
            }, 
            { 
                "action": { 
                    "type": "text", 
                    "payload": "{\"button\": \"2\"}", 
                    "label": "Primary" 
                }, 
                "color": "primary" 
            }, 
            { 
                "action": { 
                    "type": "text", 
                    "payload": "{\"button\": \"2\"}", 
                    "label": "Secondary" 
                }, 
                "color": "secondary" 
            } 
        ] 
    ] 
}

The problem is that the buttons element is an array, and json_encoding converts all associative arrays to objects, not arrays.
For example, such a structure
$buttons = [
            "action" => [
                "type" => "location"
            ]
        ];

        $keyboard = [
            'one_time' => true,
            'buttons' => $buttons
        ];

convert to the following objects:
{"one_time":true,"buttons":{"action":{"type":"location"}}}

The buttons element is an object. How can I make it an array?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yukhnovets, 2019-06-14
@AleDv

$buttons = [
["action" => [
"type" => "location"
]]
];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question