2

I have an array $suggested_cities, here it is vardumped:

array(3) {
  [15526]=>
  string(9) "Alabaster"
  [15137]=>
  string(7) "Florala"
  [37091]=>
  string(8) "Saraland"
}

When I json encode this array:

echo json_encode(array($suggested_cities));

I get this output:

[{
    "15526": "Alabaster",
    "15137": "Florala",
    "37091": "Saraland"
}]

But I need it to be:

[{
    "15526": "Alabaster"
},
{
    "15137": "Florala"
},
{
    "37091": "Saraland"
}]

How can I do that? I assume it's a "duh" answer but I just can't figure it out.

2
  • 1
    The desired JSON structure represents an array of objects - there's a big clue. Also, it would be better to use two fields per object, for id and city. Commented Dec 13, 2011 at 0:31
  • @David Caunt you're right, just had to turn suggested_cities into a multidimensional array. Also used the id as a separate field instead of the key. Thanks. Commented Dec 13, 2011 at 0:38

1 Answer 1

2

One way:

$json = json_encode(array_chunk($suggested_cities, 1, true));

DEMO

Though simply encoding $suggested_cities seems to be more straightforward.

Sign up to request clarification or add additional context in comments.

1 Comment

This works so I will pick this as best answer, but all I had to do was turn $suggested_cities into a multidimensional array and json encode that.

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.