2

I have a simple value pair array like this :

array(4) (
  [4] => (string) Barcelona
  [3] => (string) Cordoba
  [1] => (string) Granada
  [2] => (string) Jaen
)

I need to encode this to JSON to respond to an AJAX request in the following format :

[{"pk": 4, "name": "Barcelona"},
{"pk": 3, "name": "Cordoba"},
{"pk": 1, "name": "Granada"},
{"pk": 2, "name": "Jaen"}]

If I use :

json_encode($a)

I get the following :

{"4":"Barcelona","3":"Cordoba","1":"Granada","2":"Jaen","0":"Select a province"}

How do I get PHP to format my simple array to include properties in the JSON?

1
  • Have you tried iterating yet? Commented Feb 2, 2012 at 13:16

1 Answer 1

5

Just create a new array:

$data = array();

foreach($array as $key => $value) {
    $data[] = array('pk' => $key, 'name' => $value);
}

$json = json_encode($data);
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.