JCBiggar
JCBiggar

Reputation: 2507

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!

Upvotes: 2

Views: 290

Answers (3)

JCBiggar
JCBiggar

Reputation: 2507

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.

Upvotes: 0

Wrikken
Wrikken

Reputation: 70540

Use 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):

<?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;
}

Upvotes: 3

Majid Laissi
Majid Laissi

Reputation: 19808

We assume that both $value['options'] and $value['cids'] have the same length $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

getArrayFromIndex($value['options'],$i)

instead of

$value['options'][$i]

Upvotes: 0

Related Questions