0

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
1
  • yuo want to print out or to create antoher array? Commented Nov 14, 2012 at 7:53

3 Answers 3

1

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 )    
)
Sign up to request clarification or add additional context in comments.

Comments

1

It sounds like you essentially want to create a map where each output element of the map is a list. Try something like this:

<?php
function groupArrays($arrayToGroup, $arrayToGroupBy)
{
    if (count($arrayToGroup) != count($arrayToGroupBy))
        return null;

    $output = array();
    for ($i = 0; $i < count($arrayToGroupBy); $i++)
    {
        $key = $arrayToGroupBy[$i];
        $val = $arrayToGroup[$i];

        if (!isset($output[$key]))
            $output[$key] = array();

        array_push($output[$key], $val);
    }

    return $output;
}
?>

Comments

1

I just quickly create the script, this is the fastest and reliable way:

<?php
$names = ['antonio', 'luigi', 'marco', 'stefano', 'gennaro', 'pino', 'lorenzo'];
$surnames = ['bianchi', 'rossi', 'rossi', 'brambilla', 'brambilla', 'brambilla', 'brambilla'];

$final = [];
foreach ($surnames as $index => $_sur) {
    // We don't check isset $names[$index] here
    $final[$_sur][] = $names[$index];
}

var_export($final);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.