如果特定键值匹配,则合并多维数组中的其他键值

时间:2018-02-06 17:08:40

标签: php arrays multidimensional-array

我有一个多维数组,其中有几组值。我想在这里做的是合并关键值"标记"和"当然"如果键的名称"名称"比赛。到目前为止,我已经做了类似下面的操作来删除重复项:

$multi = array(
   array("name" => "Michael", "marks" => "25, 27, 34", "course" => "ABC"),
   array("name" => "Kumar", "marks" => "59, 71, 38", "course" => "DEF"),
   array("name" => "Peter", "marks" => "94, 43, 61", "course" => "JKL"),
   array("name" => "Kumar", "marks" => "83, 57, 73", "course" => "GHI"),
  );

$multiTemp = $multiNew = array();
foreach($multi as $key=>$val){
  if(array_key_exists($val['name'], $multiTemp) ) {
    continue;
  }
  $multiTemp[$val['name']] = 1;
  $multiNew[] = $val;
}

echo "<pre>";
print_r($multiNew);
echo "</pre>";

它只删除重复的值。有没有办法根据我在代码上面提到的条件合并其他两个值?就像数组$multi中的第二个和第四个数组携带name的相同值一样,我希望将markscourse合并为一个。在此先感谢您的帮助。

当前输出:

Array
(
    [0] => Array
        (
            [name] => Michael
            [marks] => 25, 27, 34
            [course] => ABC
        )

    [1] => Array
        (
            [name] => Kumar
            [marks] => 59, 71, 38
            [course] => DEF
        )

    [2] => Array
        (
            [name] => Peter
            [marks] => 94, 43, 61
            [course] => JKL
        )

)

预期产出:

Array
(
    [0] => Array
        (
            [name] => Michael
            [marks] => 25, 27, 34
            [course] => ABC
        )

    [1] => Array
        (
            [name] => Kumar
            [marks] => 59, 71, 38, 83, 57, 73
            [course] => DEF, GHI
        )

    [2] => Array
        (
            [name] => Peter
            [marks] => 94, 43, 61
            [course] => JKL
        )

)

1 个答案:

答案 0 :(得分:2)

array_reduce() + arrray_values()解决方案:

$multi = [
   ["name" => "Michael", "marks" => "25, 27, 34", "course" => "ABC"],
   ["name" => "Kumar", "marks" => "59, 71, 38", "course" => "DEF"],
   ["name" => "Peter", "marks" => "94, 43, 61", "course" => "JKL"],
   ["name" => "Kumar", "marks" => "83, 57, 73", "course" => "GHI"]
];

$result = array_values(array_reduce($multi, function($r, $a){
    $name = $a['name'];
    if (isset($r[$name])){
        $r[$name]['marks'] .= ', ' . $a['marks'];
        $r[$name]['course'] .= ', ' . $a['course'];
    } else {
        $r[$name] = $a;
    }
    return $r;
}, []));

print_r($result);

输出:

Array
(
    [0] => Array
        (
            [name] => Michael
            [marks] => 25, 27, 34
            [course] => ABC
        )

    [1] => Array
        (
            [name] => Kumar
            [marks] => 59, 71, 38, 83, 57, 73
            [course] => DEF, GHI
        )

    [2] => Array
        (
            [name] => Peter
            [marks] => 94, 43, 61
            [course] => JKL
        )
)

http://php.net/manual/en/function.array-reduce.php