Which is the most effective way to group array elements respect to the values of another array in PHP?
Example:
names = [antonio, luigi, marco, stefano, gennaro, pino, lorenzo];
surnames = [bianchi, rossi, rossi, brambilla, rossi, rossi, brambilla];
expected result:
bianchi:
antonio
rossi:
luigi, marco, gennaro, pino
brambilla:
stefano, lorenzo
Try this
foreach ($surnames as $key => $value) {
if (isset($result[$value])) {
if (!is_array($result[$value])) $result[$value] = (array) $result[$value];
array_push($result[$value], $names[$key]);
}
else
$result[$value]= $names[$key];
}
print_r($result);
Output
Array (
[bianchi] => antonio
[rossi] => Array ( [0] => luigi, [1] => marco, [2] => gennaro, [3] => pino )
[brambilla] => Array ( [0] => stefano, [1] => lorenzo )
)
Otherwise
foreach ($surnames as $key => $value) { $result[$value][] = $names[$key]; }
Output
Array (
[bianchi] => Array ( [0] => antonio )
[rossi] => Array ( [0] => luigi, [1] => marco, [2] => gennaro, [3] => pino )
[brambilla] => Array ( [0] => stefano, [1] => lorenzo )
)