Dylan Cross
Dylan Cross

Reputation: 5986

Trying to put multiple data in php/json array

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)

Upvotes: 3

Views: 6204

Answers (3)

Treffynnon
Treffynnon

Reputation: 21563

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);
}

Upvotes: 5

faq
faq

Reputation: 3086

do something like:

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

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

Upvotes: 0

Nobita
Nobita

Reputation: 23713

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);

Upvotes: 0

Related Questions