JSON PHP Key with same name

154
May 25, 2018, at 1:40 PM

Chatfuel gives this as a way to respond back:

{
"messages": [
{"text": "Welcome to the Chatfuel Rockets!"},
{"text": "What are you up to?"}
]
}

I want to output something like this with My text, but keys with same value are not possible, since it outputs the first key with the last value

<?php
 $arr = array(array('messages' => array('text' => "Text 1", 'text' => "text 
 2")));

 if ("test" == "test"){
  echo json_encode($arr);
 }

Output: [{"messages":{"text":"text 2"}}]

How do I output a way like requested by chatfuel?

Answer 1

I'm going to make this fairly verbose so you can see how the structure is being generated. There is an outer object that contains a "messages" property which is an array of "message" objects each with a "text" property.

V1

$json = new stdClass();
$json->messages = array();
$message = new stdClass();
$message->text = 'Welcome to the Chatfuel Rockets!';
$json->messages[] = $message;
$message = new stdClass();
$message->text = 'What are you up to?';
$json->messages[] = $message;
echo json_encode( $json, JSON_PRETTY_PRINT );

V2

$json = array(
  'messages' => array(
    array(
      'text' => 'Welcome to the Chatfuel Rockets!'
    ),
    array(
      'text' => 'What are you up to?'
    ),
  )
);
echo json_encode( $json, JSON_PRETTY_PRINT );
Answer 2
$arr = ['messages' => [['text' => 'Text 1'], ['text' => 'Text 2']]];
echo json_encode($arr, JSON_PRETTY_PRINT);

Output:

{
    "messages": [
        {
            "text": "Text 1"
        },
        {
            "text": "Text 2"
        }
    ]
}
READ ALSO
reroute query string to directory in php

reroute query string to directory in php

I am using this code from GithubThis is a proxy site and currently, if someone enters a link, it goes to a query_string to complete your request

115
next page or page 2 reset the searched value in pagination

next page or page 2 reset the searched value in pagination

I am a new user hereI am trying to create a simple pagination with search filter for a CRM system

153
I can not access the wordpress desktop but I&#39;m not wrong either

I can not access the wordpress desktop but I'm not wrong either

how are you? My problem is the following…

102
PHP dns_get_record rate limit?

PHP dns_get_record rate limit?

I frame this question within PHP/dns_get_record context, although it applies to other languages/API's as well:

128