theplau
theplau

Reputation: 980

How do I get only the first value for each item in a multidimensional array?

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

Answers (5)

Grzegorz
Grzegorz

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

devpro
devpro

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

Ann
Ann

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

Girish Patidar
Girish Patidar

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

Gal Silberman
Gal Silberman

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

Related Questions