3

This is probably quite simple to do.. but I just can't think of how to do this.

I have a photo upload script, I want to return two types of data in an array, right now I just have one set of data for the photo returned.

right now I do this:

 $photos = array();

 ///Script for photo upload etc.
 array_push($photos, $newPhotoToAdd)

 //then when it's finished uploading each photo i do json_encode:
 print json_encode($photos);

all of this works perfect, however now I want to return another set of data with each photo.

I need to do something like:

 array_push($photos, ['photoID'] = $photoID, ['photoSource'] = $newPhotoToAdd)

3 Answers 3

5

Original Question

You can just push an array on instead of newPhotoToAdd like the following:

$photos = array();
// perform upload
$photos[] = array(
    'photoID' => $photoID,
    'photoSource' => $newPhotoToAdd
);
print json_encode($photos);

You'll notice that I have swapped array_push() DOCs for the array append syntax of [] DOCs as it is simpler and with less overhead:

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

From comments: printing it out in JavaScript

You are dealing with an array of objects so you need to loop over them:

for(var i in json) {
    alert(json[i].photoID);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, now I'm having trouble trying to use this in javascript though. It's not working as I thought it would. var json = JSON.parse(content); alert(json.photoID); this returns undefined
0

You want to create an array like this:

$photo = array('photoID' => $photoID, 'photoSource' => $newPhotoToAdd);

Then you want to do the push as you did before with this new array:

array_push($photos, $photo);

Comments

0

do something like:

$photos = array();
array_push($photos, array('photoID'=>$photoID,'photoSource'=>$newPhotoToAdd));

foreach ($photos as $photo) {
print json_encode($photo);
}

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.