简体   繁体   English

将数组元素相对于另一个数组的值进行分组

[英]group array elements respect to the values of another array

I know it's a simple question, but I didn't succeed in finding the answer, yet... 我知道这是一个简单的问题,但是我没有成功找到答案。

Which is the most effective way to group array elements respect to the values of another array in PHP? 在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

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

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM