Reputation: 980
I have a multidimensional array with product names and each product has 1 or more (up to 5) images. I'm trying to get just the product name and the first
image, but the way I have it it prints all the images. How do I get just the first one for each?
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
foreach ($result['images'] as $image) {
echo 'Image: '.$image['image_url'];
echo "\n";
}
}
Which prints like:
Title: Blah
Image: http://1..
Image: http://2..
Image: http://3..
I want to get just
Title: Blah
Image: http://1..
I tried modifying it to
echo 'Image: '.$image['full_image_url'][0];
but that didn't work. Any ideas?
Upvotes: 0
Views: 65
Reputation: 3608
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
echo 'Image: ' . $result['images'][0]['image_url'];
echo "\n";
}
Alternatively (if you dont know first index for example)
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
foreach ($result['images'] as $image) {
echo 'Image: '.$image['image_url'];
echo "\n";
break;
}
}
Upvotes: 3
Reputation: 16117
If you know the index id than you can use like that:
foreach ($my_array as $result) {
echo 'Title: '.$result['title'];
echo 'Image: '. $result['image_url'][0];
}
And alternate is:
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
foreach ($result['images'] as $image) {
echo 'Image: '.$image['image_url'];
return;
}
}
Third solution is provided by @gacek
Upvotes: 1
Reputation: 471
foreach ($my_array['results'] as $result)
{
echo 'Title: '.$result['title'];
foreach ($result['images'] as $image)
{
echo 'Image: '.$image['image_url'];
echo "\n";
break;
}
}
Upvotes: 1
Reputation: 364
If you want to get title and first element of image array please try below code :
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
echo 'Image: '.$result['images']['0']['image_url'];
echo "\n";
}
Upvotes: 1
Reputation: 3894
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
foreach ($result['images'] as $image) {
echo 'Image: '.$image['image_url'];
echo "\n";
break;
}
}
Upvotes: 1