Search code examples
phparraysforeach-loop-container

PHP 2 Arrays in Foreach-loop?


I have used array_combine to print out 2 different arrays, but the function use first array for index, and he supress values with same content. I need printout even when has a same value. Some tip about how resolve this?

function mostra_2com($valor, $valor2){
    echo "<table class='bs'><tr><td><b>Atividades</b></td><td><b>Opiniões</b></td></tr>";
    foreach (array_combine($valor, $valor2) as $val => $val2) 
    echo "<tr><td>".$val." </td><td> ".$val2."<br></td></tr>";
    echo"</table>";
}
enter code here

Solution

  • You probably want to use MultipleIterator:

    $mi = new MultipleIterator(MultipleIterator::MIT_NEED_ALL | MultipleIterator::MIT_KEYS_ASSOC);
    $mi->attachIterator(new ArrayIterator($valor), 'val');
    $mi->attachIterator(new ArrayIterator($valor2), 'val2');
    
    foreach ($mi as $values) {
        extract($values);
        echo '<tr><td>', $val, '</td><td>', $val2, '<br></td></tr>';
    }
    

    It iterates over both arrays at the same time and for each iteration yields $values as an array like this:

    array('val' => 1, 'val2' => 4);
    

    In this example 1 and 4 would come from $valor and $valor2 respectively. I then use extract() inside the loop to bind those keys to actual variables.