Join php arrays by allocating combined values between the two

2

I have the following arrays:

$corretor = array(
  'Carlos',
  'Andre',
  'Rosinei',
  'Vinicius',
  'Thales'
);
$comissao = array(
   5,
   3,
   3,
   3,
   2
);

How do I merge both, printing the result as follows:

  

Carlos - 5% | Andre - 3% | Rosinei - 3% | Vinicius - 3% | Thales - 2%

    
asked by anonymous 09.05.2016 / 19:36

1 answer

2

Assuming that both arrays have the same number of elements, you need to create a way to iterate through these arrays and use the iteration index to use data from each array.

If you use array_map nor do you need to know the iteration index and you can mix both directly like this:

function misturar($nome, $perc){
    return $nome.' - '.$perc.'%';   
}

$c = array_map("misturar", $corretor, $comissao);
echo implode($c, ' | ');

Example: link

Although in this case find it simpler with array_map, you can also do this:

$res = '';
for ($i = 0; $i < count($corretor); $i++){
    $res.= $corretor[$i].' - '.$comissao[$i].'% | ';    
}

echo substr($res, 0, -3);

Example: link

    
09.05.2016 / 21:13