Merge php arrays by allocating combined values between the two

Asked

Viewed 259 times

2

I have the following arrays:

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

How do I join both, printing result as follows:

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

  • 1

    You just want to merge the result to display, or you want to create a new array with the data in "merge"?

  • http://answall.com/questions/27631/mesclar-arrays-em-php

  • 1

    @Diegof thanks for helping, Sergio’s response was exactly what I needed.

1 answer

2


Assuming that both arrays have the same number of elements you have to create a way to iterate those arrays and use the iteration index to use data from each one.

If you use the array_map you don’t even need to know the iteration index and you can mix the two directly like this:

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

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

Example: https://ideone.com/ck4nFA

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

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

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

Example: https://ideone.com/TyoYzm

  • was just that. Is there any way to delete blank values from the array?

  • @Igorsilva refers to cases where both arrays have a blank value at the same position?

  • 1

    If that’s the case, you can use the array_filter() https://ideone.com/OFbyLl for the first case, and for the second case: https://ideone.com/O5UmFI

  • 1

    Really solved my problem. I thank you for the strength!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.