0

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?

2 Answers 2

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 );
Sign up to request clarification or add additional context in comments.

Comments

0
$arr = ['messages' => [['text' => 'Text 1'], ['text' => 'Text 2']]];
echo json_encode($arr, JSON_PRETTY_PRINT);

Output:

{
    "messages": [
        {
            "text": "Text 1"
        },
        {
            "text": "Text 2"
        }
    ]
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.