group数组元素相对于另一个数组的值

时间:2012-11-14 07:52:55

标签: php arrays grouping

我知道这是一个简单的问题,但我没有成功找到答案,但是......

哪种方法是将数组元素分组到PHP中另一个数组的值?

示例:

names = [antonio, luigi, marco, stefano, gennaro, pino, lorenzo];
surnames = [bianchi, rossi, rossi, brambilla, rossi, rossi, brambilla];

预期结果:

bianchi:
antonio

rossi: 
luigi, marco, gennaro, pino

brambilla:
stefano, lorenzo

3 个答案:

答案 0 :(得分:1)

听起来你本质上想要创建一个地图,其中地图的每个输出元素都是一个列表。尝试这样的事情:

<?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;
}
?>

答案 1 :(得分:1)

我只是快速创建脚本,这是最快速可靠的方法:

<?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);

答案 2 :(得分:1)

试试这个

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);

输出

Array (
    [bianchi] => antonio
    [rossi] => Array ( [0] => luigi, [1] => marco, [2] => gennaro, [3] => pino )
    [brambilla] => Array ( [0] => stefano, [1] => lorenzo )    
)

否则

foreach ($surnames as $key => $value) { $result[$value][] = $names[$key]; }

输出

Array (
    [bianchi] => Array ( [0] => antonio )
    [rossi] => Array ( [0] => luigi, [1] => marco, [2] => gennaro, [3] => pino )
    [brambilla] => Array ( [0] => stefano, [1] => lorenzo )    
)