Question

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
Was it helpful?

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.

OTHER TIPS

You could use array_merge()

$a = array('1', '2');
$b = array('1', '4');
$c = array_merge($a,$b);
print_r($c);
// Array ( [0] => 1 [1] => 2 [2] => 1 [3] => 4 );

Try this instead:

function my_array_combine($keys, $values) {
     $result = array();
     foreach ($keys as $i => $k) {
         $result[$k][] = $values[$i];
     }
     array_walk($result, create_function('&$v', '$v = (count($v) == 1)? array_pop($v): $v;'));
     return    $result;
 }

ripped from http://php.net/manual/en/function.array-combine.php It should be possible to make this code alot faster, if you are doing <1,000,000 items, not a problem as is.

Maybe a case for an SPL multipleiterator:

$valor = array(10, 20, 30);
$valor2 = array(15, 10, 15);

$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 $details) {
    echo "<tr><td>" . $details['val'] . "</td><td>" . $details['val2'] . "<br></td></tr>";
}

PHP > 5.5

$valor = array(10, 20, 30);
$valor2 = array(15, 10, 15);

$mi = new MultipleIterator();
$mi->attachIterator(new ArrayIterator($valor));
$mi->attachIterator(new ArrayIterator($valor2));
foreach($mi as list($val, $val2)) {
    echo "<tr><td>" . $val. "</td><td>" . $val2. "<br></td></tr>";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top