William Chandra William Chandra - 2 months ago 8
PHP Question

combine two arrays in php in unique case

I have the following 2 arrays variable.

$a = array("triple","triple","double","single","single");
$b = array("444","555","33","2","3");


i need to convert that 2 arrays to be this array pattern

$array = array(
"triple"=>array("444","555"),
"double"=>array("33"),
"single"=>array("2","3")
);


so that i can get the result like this

triple(444 | 555) double(33) single(2 | 3)


anyone can help me? thanks

Answer

Just use array_combine, $b as keys and $a as values, then transfer to a new container grouping them with the key:

$array = array();
foreach(array_combine($b, $a) as $k => $v) {
    $array[$v][] = $k;
}

For presentation purposes, just implode them:

foreach($array as $key => $numbers) {
    echo $key , '(' , implode(' | ', $numbers), ')', ' ';
}
Comments