1

I need to generate from an array this json:

{
 “authentication”: {
 “username”: “test”,
 “password”: “test”
},
“msg”: [
 {
  “name”: “jDOE”,
  “msg”: ���Hello”,
  “recipients”: [
   {
    “gm”: “385951111111”
   },
   {
    “gm”: “385952222222”
   },
   {
    “gm”: “385953333333”
   }
  ]
 }
]

}

This is easy creating just the array but, if you see the GM key repeats 3 times. In PHP I think we can't have duplicate keys in associative arrays. So how can I replicate this....maybe an object? a string?....after generate the structure I use the funciton json_encode to generate the json.

This is the array I'm using to generate the json:

$data = array(
  'authentication' => array(
  'username' => 'BisA4Corp1',
  'password' => 'Xls2smst5',
),
'messages' => array(
  'name' => 'jDOE',
  'msg' => 'Mensaje de prueba',
  'recipients' => array('gm' => '3387967849'),
),
);

Thanks!

2

2 Answers 2

1

recipients must be an array itself, so your array should be like this:

 $data = array(
  'authentication' => array(
     'username' => 'BisA4Corp1',
     'password' => 'Xls2smst5',
 ),
 'messages' => array(
     'name' => 'jDOE',
     'msg' => 'Mensaje de prueba',
     'recipients' => array(
         array('gm' => '3387967849'),
         array('gm' => '3387967849'),
         array('gm' => '3387967849'),
      ),
  ),
);
Sign up to request clarification or add additional context in comments.

Comments

0

Use multidimential array as php doesnt allow your code.

<?php
$data = array(
  'authentication' => array(
  'username' => 'BisA4Corp1',
  'password' => 'Xls2smst5',
),
'messages' => array(
  'name' => 'jDOE',
  'msg' => 'Mensaje de prueba',
  'recipients' => array( array('gm' => '3387967849'), array('gm' => '385952222222'))
)
);

echo "<pre>";
print_r($data);

Output

Array
(
    [authentication] => Array
        (
            [username] => BisA4Corp1
            [password] => Xls2smst5
        )

    [messages] => Array
        (
            [name] => jDOE
            [msg] => Mensaje de prueba
            [recipients] => Array
                (
                    [0] => Array
                        (
                            [gm] => 3387967849
                        )

                    [1] => Array
                        (
                            [gm] => 385952222222


    )

            )

    )

)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.