我有一个带有产品名称的多维数组,每个产品都有一个或多个(最多5个)图像。我试图只获取产品名称和first
图像,但我的方法是打印所有图像。如何为每个人只获取第一个?
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
foreach ($result['images'] as $image) {
echo 'Image: '.$image['image_url'];
echo "'n";
}
}
打印如下:
Title: Blah
Image: http://1..
Image: http://2..
Image: http://3..
我只想得到
Title: Blah
Image: http://1..
我试着把它修改成
echo 'Image: '.$image['full_image_url'][0];
但那没用。有什么想法吗?
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
echo 'Image: ' . $result['images'][0]['image_url'];
echo "'n";
}
或者(例如,如果您不知道第一个索引)
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
foreach ($result['images'] as $image) {
echo 'Image: '.$image['image_url'];
echo "'n";
break;
}
}
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
foreach ($result['images'] as $image) {
echo 'Image: '.$image['image_url'];
echo "'n";
break;
}
}
如果您想获得图像数组的标题和第一个元素,请尝试以下代码:
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
echo 'Image: '.$result['images']['0']['image_url'];
echo "'n";
}
foreach ($my_array['results'] as $result)
{
echo 'Title: '.$result['title'];
foreach ($result['images'] as $image)
{
echo 'Image: '.$image['image_url'];
echo "'n";
break;
}
}
如果你知道索引id,你可以这样使用:
foreach ($my_array as $result) {
echo 'Title: '.$result['title'];
echo 'Image: '. $result['image_url'][0];
}
备选方案是:
foreach ($my_array['results'] as $result) {
echo 'Title: '.$result['title'];
foreach ($result['images'] as $image) {
echo 'Image: '.$image['image_url'];
return;
}
}
第三个解决方案由@gacek