0

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

哪个是根据 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
4

3 回答 3

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;
}
?>
于 2012-11-14T07:58:42.527 回答
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 )    
)
于 2012-11-14T08:15:32.033 回答
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);
于 2012-11-14T08:09:03.373 回答