简体   繁体   English

如何在一个foreach循环中显示两个数组?

[英]How to display two arrays in one foreach loop?

am storing two arrays in one column.first one is images stored as image1* image2 *...etc and second one is descriptions as description1* description2 *...etc. 我将两个数组存储在一列中。第一个是存储为image1 * image2 * ...等的图像,第二个是作为description1 * description2 * ...等的描述 i want to use these two set of arrays in one foreach loop.Please help. 我想在一个foreach循环中使用这两套数组。请帮忙。

Just reference the key: 只需引用密钥:

foreach ($images as $key => $val) {
    echo '<img src="' . $val . '" alt="' . $descriptions[$key] . '" /><br />';
}

You can't use foreach , but you can use for and indexed access like so. 您不能使用foreach ,但是可以像这样使用for和索引访问。

$count = count($images);
for ($i = 0; $i < $count; $i++) {
    $image = $images[$i];
    $description = $descriptions[$i];
}

You could use array_combine to combine the two arrays and then use a foreach loop. 您可以使用array_combine合并两个数组,然后使用foreach循环。

$images = array('image1', 'image2', ...);
$descriptions = array('description1', 'description2', ...);

foreach (array_combine($images, $descriptions) as $image => $desc) {
  echo $image, $desc;
}

It does not seem possible by foreach loop. 通过foreach循环似乎不可能。 Instead try using for loop. 而是尝试使用for循环。 If you are sure both your arrays are of the same size, then try using following code: 如果确定两个数组的大小相同,请尝试使用以下代码:

for ($i=0; $i<sizeof(array1); $i++) {
     echo $arrray1[$i];
     echo $arrray2[$i];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM