2

I have a for loop, it returns an id and the name of all the images a user has.

 $from1 = 1;
 $from2 = 10;

 for ($i=$from1; $i < $from2; $i++) {
     if (($i % 5) == 0) 
     $idTemp = $id1[$i];

     echo $idTemp;
     echo $name[$i];
 }

Instead of echoing out the data, I wish to place it into a json response, like this:

"images":[
    "1":{"id":"1234","name":"thisisaname"},
    "2":{"id":"4332","name":"namename"}
]

But i can't seem to work out how to create json arrays inside a loop. Also how would i then loop through to decode the json?

Can anyone help? Cheers for any help in advance, Jamie

0

1 Answer 1

4

On the server side (PHP) to print the json response, first create the php array that has the same structure, then you can encode it with json_encode:

$from1 = 1;
$from2 = 10;

$json = array('images' => array());
for ($i=$from1; $i < $from2; $i++) {
    if (($i % 5) == 0) {
        $json['images'][$i] = array(
            'id' => $id1[$i],
            'name' => $name[$i]
        );
     }
}

echo json_encode($json);

On the client side (JS) you will receive say a data object:

$.getJSON(url, function(data) {
    for (x in data.images) {
        data.images[x].id;
        data.images[x].name;
    }
}
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.