[英]Multiple foreach with two arrays
I have been trying to figure this out all day... but can't seem to get it working.我一整天都在试图解决这个问题……但似乎无法让它发挥作用。
I have this code that works:我有这个有效的代码:
<?php foreach ($value['options'] as $option) { ?>
<option><?php echo $option; ?></option>
<?php } ?>
and it displays correctly with the array listed as my options.它正确显示,数组列为我的选项。 But I wanted a value with each array by splilting another array I had into an option by doing this:但是我希望通过将另一个数组拆分为一个选项来为每个数组分配一个值:
<?php foreach ($value['options'] as $option) {
foreach ($value['cids'] as $cid) { ?>
<option value="<?php echo $cid; ?>"><?php echo $option; ?></option>
<?php } } ?>
Whenever I do that, it my options are multiplied in every possible way, which I dont want.每当我这样做时,我的选择就会以各种可能的方式成倍增加,这是我不想要的。 How would I go about doing something like this我将如何去做这样的事情
<?php foreach ($value['options'] as $option AND $value['cids'] as $cid) {
echo $option;
echo $cid;
} ?>
I know that doesn't work... just want something similar.我知道那行不通……只想要类似的东西。 Thanks in advance!提前致谢!
Use MultipleIterator
:使用MultipleIterator
:
<?php
$array1 = range(1,5);
$array2 = range(6,10);
$iterator = new MultipleIterator();
$iterator->attachIterator(new ArrayIterator($array1));
$iterator->attachIterator(new ArrayIterator($array2));
foreach($iterator as $items){
echo $items[0].' - '.$items[1];
}
?>
Of course, real old school (you younguns don't know how much foreach
has spoiled you):当然,真正的老派(你们年轻人不知道foreach
宠坏了你多少):
<?php
$array1 = range(1,5);
$array2 = range(6,10);
//reset array pointers to be sure
reset($array1);
reset($array2);
while((list(,$a) = each($array1)) && (list(,$b) = each($array2))){
echo $a .':'.$b.PHP_EOL;
}
We assume that both $value['options']
and $value['cids']
have the same length $length
:我们假设$value['options']
和$value['cids']
具有相同的长度$length
:
<?php for($i=0 ; $i < $length; $i++) { ?>
<option value="<?php echo $value['options'][$i]; ?>"><?php echo $value['cids'][$i]; ?></option>
$arr[$i];
<?php } ?>
If your array, however, is associative, you can use something like :但是,如果您的数组是关联的,则可以使用以下内容:
function getArrayFromIndex($arr, $ind)
{
$i==0;
foreach ($arr as $key => $value) {
if ($i==$ind)
return $key;
}
}
to get your Nth element by calling通过调用获取您的第 N 个元素
getArrayFromIndex($value['options'],$i)
instead of代替
$value['options'][$i]
First of all, thank you all for the answers.首先谢谢大家的解答。 It led me to the right direction.它引导我走向正确的方向。 Here is what I did to get this working.这是我为使其正常工作所做的工作。
<?php
$myoptions = array_combine($value['options'], $value['cid']);
foreach ($myoptions as $option => $cid) { ?>
<option value="<?php echo $cid; ?>"><?php echo $option; ?></option>
<?php } ?>
I did an array_combine
to echo my values.我做了一个array_combine
来回应我的价值观。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.