Basically I am calling an API to get an array of URLs for an image.
I start off by doing this
$mainResponse = array(
"result" => array(
),
"ack" => "success"
);
I will then make my call and add the image URLs like this:
foreach($resp->Item as $item) {
$picture = $item->PictureURL;
array_push($mainResponse['result'], $picture);
}
Finally, I will echo this out to me.
echo json_encode($mainResponse);
The problem I am facing is that my response is
{"result":[{"0":"IMAGE_URL","1":"IMAGE_URL"}],"ack":"success"}
Where I would want it to be like....
{"result":["IMAGE_URL","IMAGE_URL"],"ack":"success"}
Where did I go wrong in my PHP code?
Seems like $picture is a associative array, change the foreach loop with this:
foreach($resp->Item->PictureURL as $item) {
foreach($item as $_item){
array_push($mainResponse['result'],$_item);}
}
For some reason this API returns an object instead of an array.
You can just do:
foreach ($resp->Item as $item) {
$picture = $item->PictureURL;
array_merge($mainResponse['result'], (array)$picture);
}
You can use array_push if you want every item to have separate pictures.
Related
I have a php function that currently looks like this
function renderJson(PageArray $items) {
$myData = array();
$myData['title'] = [];
$myData['url'] = [];
// cycle through all the items
foreach($items as $item) {
array_push($myData["title"],$item->title);
array_push($myData["url"],$item->url);
}
return json_encode($myData);
}
It currently works in this shape as output
{"title":["A","B"],"url":["A","B"]}
But this is what I am trying to achieve
{"title":["A"],"url":["A"]},{"title":["B"],"url":["B"]}
I am trying to return it as a JSON encode.The $item->title and $item->url returns a string.Any help would be great.
So now you get this :
{"title":["A","B"],"url":["A","B"]}
But you want this :
{"title":["A"],"url":["A"]},{"title":["B"],"url":["B"]}
What you want is add a new "item" each time you loop and each item have a title and an url. Right now you return an array that contain 2 sub-array : one for the title, one for the url.
Try this way :
function renderJson(PageArray $items) {
// Your result array
$myData = array();
// cycle through all the items
foreach($items as $item) {
// Each time you loop, you add a new array in your main array with a title and an URL
$myData[] = array(
"title" => $item->title,
"url" => $item->url
);
}
return json_encode($myData);
}
I used [] because he does what you need : push element at the end of your main array. It's the short way to use array_push(). Here is the documentation for more details : http://php.net/manual/en/function.array-push.php
The output will be :
[{"title":["A"],"url":["A"]},{"title":["B"],"url":["B"]}]
What you want to return is not, of course, valid json. At this point return an array containing those two objects (i.e., push the whole $item to $myData)
function renderJson(PageArray $items) {
$myData = array();
// cycle through all the items
foreach($items as $item) {
array_push($myData,['title' => $item->title, 'url' => $item->url]);
}
return json_encode($myData);
}
which gives you something in the form of
[{"title":"A","url":"A"},{"title":"B","url":"B"}]
You create invalid JSON by concatenation your JSON by comma. Either get your client (speak receiver of the json data) to split the result by comma and then parsing each JSON by its own.
Otherwise you could create a "big" JSON string, containing both (or all if there are more) of your JSON data.
Just create an array in PHP, add a new element for each JSON data, then json_encode() it and go over it by a loop in your client.
What you will use in the end, doesnt really matter that much, but I would use the second approach by a lot over the first, since it´s much cleaner.
Hello I can't figure out how to loop through this json encoded array and for each object, get all its values. I need each value as a variable for itself.
echo json_encode($formulars);
This is what i get when i echo it out
[{"project_name":"polle","type":"support","title":"vi","reason":"prover","solution":"igen","comments":"okay ","date_stamp":"2013-08-20 14:06:37","used_time":132},{"project_name":"dolla","type":"support","title":"lolol","reason":"skl","solution":"dskal","comments":"kflafda ","date_stamp":"2013-08-20 14:11:36","used_time":210},{"project_name":"polle","type":"fejl","title":"lol","reason":"aksdl","solution":"fdjks","comments":"djsks ","date_stamp":"2013-08-20 14:13:27","used_time":1230}]
I have tried this piece of code and I managed to get out the project_name from the first object and that's it:
foreach ($formulars as $current => $project_name) {
$project_name['project_name'];
}
So is there any way i can get all the variables for each object in my array instead of just the project_name?
Like this:
foreach ($formulars as $current){
$projectName = $current['project_name'];
$type = $current['type'];
$reason = $current['reason'];
}
Thanks in advance
Seems like you have an objects inside an array. So you will need to loop through the array and get each object. Just JSON_DECODE your encoded string like below.
Perhaps:
$data = json_decode($formulars,true);
/* Since it's only one object inside the array, you could just select element zero, but I wil loop*/
//You should now be able to do this
foreach ($data as $current){
$projectName = $current['project_name'];
$type = $current['type'];
$reason = $current['reason'];
}
The reason I loop is because there is a object inside an array(Javascript way I think).
Use json_decode to convert the json object to an array; then use foreach to loop through the array. That should work.
<?php
$arr_json = json_decode($formulars);
foreach($arr_json as $key => $value)
//Code to perform required actions
?>
This should give you some ideas.
Use json_decode (with TRUE for getting an associative array)to convert your JSON object to an associative array. After that, you can use a foreach loop to traverse through your multidimensional array and print the required values.
Code:
$json = json_decode($string, true);
foreach ($json as $key => $value) {
foreach($value as $key2 => $value2) {
echo $value2."\n";
}
}
Working Demo!
I am trying to print the contents of a nested array, but it simply returns "Array" as a string yet will not iterate with a foreach loop. The arrays are coming from a mongodb find(). The dataset looks like this:
User
Post_Title
Post_Content[content1,content2,content3]
I am trying to get at the content1,2,3.
My current code looks like this:
$results = $collection->find($query);
foreach ($results as $doc)
{
echo $doc['title']; //this works
$content[] = $doc['content'];
print_r($content); //this prints "Array ( [0] => Array )"
foreach ($content as $item)
{
echo $item;
}
}
All this code does is print the Title, followed by Array ( [0] => Array ), followed by Array.
I feel quite stupid to not figure out something that seems so basic. Most posts on stack overflow refer to multidimensional associative arrays - in this case, the top level array is associative, but the content array is indexed.
I have also tried
foreach ($doc['content'] as $item)
But that gives
Warning: Invalid argument supplied for foreach()
I even tried iterating over the returned array again using a nested foreach, like the following:
foreach ($results as $doc)
{
echo $doc['title']; //this works
$content[] = $doc['content'];
print_r($content); //this prints "Array ( [0] => Array )"
foreach ($content as $item)
{
foreach ($item as $next_item)
{
echo $next_item;
}
echo $item;
}
}
The second foreach failed with an invalid argument..
Any thoughts would be greatly appreciated.
edit: perhaps it has something to do with how I am inserting the data to the DB. That code looks like this
$title = $_POST['list_title'];
$content[] = $_POST['list_content1'];
$content[] = $_POST['list_content2'];
$content[] = $_POST['list_content3'];
$object = new Creation();
$object->owner = "$username";
$object->title = "$title";
$object->content = "$content";
$object->insert();
Is this not the proper way to add an array as a property to a class?
The issue is some of array content is an array while other parts are strings. You should test for the sub content $doc being an array using is_array(). If it is, loop through the $doc like you would any other array, and if it isn't, you can echo the content (may need to test the content type before doing this if you're uncertain as to what content it can be)
The problem is in the code that you are saving data. You should replace the following line
$object->content = "$content";
with
$object->content = $content;
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)
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);
}
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);
do something like:
$photos = array();
array_push($photos, array('photoID'=>$photoID,'photoSource'=>$newPhotoToAdd));
foreach ($photos as $photo) {
print json_encode($photo);
}
I'm using SimpleXML to extract images from a public feed # Flickr. I want to put all pulled images into an array, which I've done:
$images = array();
foreach($channel->item as $item){
$url = $path->to->url;
$images[] = $url;
}
From this I can then echo out all the images using:
foreach($images as $image){
//output image
}
I then decided I wanted to have the image title as well as the user so I assumed I would use:
$images = array();
foreach($channel->item as $item){
$url = $path->to->url;
$title = $path->to->title;
$images[$title] = $url;
}
I thought this would mean by using $image['name of title'] I could output the URL for that title, but it gives an Illegal Offset Error when I run this.. and would only have the title and url, but not the user.
After Googling a bit I read you cannot use _ in the array key, but I tried using:
$normal = 'dddd';
$illegal = ' de___eee';
$li[$normal] = 'Normal';
$li[$illegal] = 'Illegal';
And this outputs right, ruling out _ is illegal in array keys (..I think).
So now I'm really confused why it won't run, when I've used print_r() when playing around I've noticed some SimpleXML objects in the array, which is why I assume this is giving an error.
The ideal output would be an array in the format:
$image = array( 0 => array('title'=>'title of image',
'user'=>'name of user',
'url' =>'url of image'),
1 => array(....)
);
But I'm really stumped how I'd form this from a foreach loop, links to reference as well as other questions (couldn't find any) are welcome.
$images = array();
foreach ($channel->item as $item){
$images[] = array(
'title' => $item->path->to->title,
'url' => $item->path->to->url
);
}
foreach ($images as $image) {
echo "Title: $image[title], URL: $image[url]\n";
}
Underscore is not forbidden symbol for array keys, the only problem you might run to, that titles some times overlap and you might loose some items in your array. Most correct way would be deceze example
If you prefer associative array you can use image path as array key and title as value.