0

Currently I need to build an API to output as json format, and what I currently do (as example) is the following:

$array=array();
$array['firstname']="John";
$array['lastname']="Doe";
$array['cities']=array();
$array['cities']['name']=array("London","Brighton");
$array['cities']['population']=array("12000000","500000");
echo json_encode($array);

The output is:

{"firstname":"John","lastname":"Doe","cities":{"name":["London","Brighton"],"population":["12000000","500000"]}}

However I was told that this is incorrect, and the output needs to be

{"firstname":"John","lastname":"Doe","cities":[{"name":["London","Brighton"],"population":["12000000","500000"]}]}

(note the square brackets in the output). The reason was claimed that cities itself needs to be specified as an array since $array['cities'] is an array.

My questions are:

1) Is it custom to add square brackets in these cases to indicate it is an array?

2) How can I change my php code in order to have these square-brackets in the output?

help appreciated

Thanks Patrick

4
  • 2
    Are you sure that's what the output needs to be? I'd expect London and Brighton (and their respective populations) to be in separate objects in the cities array. Commented Sep 16, 2016 at 8:41
  • Hi, I was surprised too, but was asked if I could change it to the 'correct' format, by having it in square-brackets. My understanding is that key-value arrays are always objects in javascript, but since cities[] itself is an array, it needs to be casted as such. Commented Sep 16, 2016 at 8:46
  • I think they will tell you it's wrong, but 3v4l.org/KeZOh Commented Sep 16, 2016 at 8:49
  • that does the trick yes ...:) Commented Sep 16, 2016 at 8:57

1 Answer 1

1

It's here

$array=array();
$array['firstname']="John";
$array['lastname']="Doe";
$array['cities']=array();
$array['cities'][]=array(
                        'name'=>array("London","Brighton"),
                        'population'=>array("12000000","500000")
                   );
echo json_encode($array);
Sign up to request clarification or add additional context in comments.

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.