1

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?

3
  • can you print_r($resp->Item); please? Commented Aug 3, 2019 at 14:27
  • Some codes are missed here. You can't convert array to object implicitly. But PictureURL property can be array of strings. Then you'll get this output. Commented Aug 3, 2019 at 14:27
  • ahhh @u_mulder you are right. i forgot to add that into there, but I did figure out the issue. If I do strval($pic) ill get the string value and not a set of objects. Commented Aug 3, 2019 at 14:39

2 Answers 2

1

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);}
}
Sign up to request clarification or add additional context in comments.

2 Comments

This is not dynamic. Not a good answer at all. Not always will there be 2 pictures. There may be 1, 2, 3... n or even 0.
@soldfor check now
1

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.

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.