合并具有相同名称的php数组元素

时间:2015-05-27 19:41:06

标签: php arrays multidimensional-array

我有这个php数组

array [
    [0] => array [
                   name => 'a',
                   service => 'x1' 
                 ],
    [1] => array [
                   name => 'a',
                   service => 'x2' 
                 ],
    [2] => array [
                   name => 'a',
                   service => 'x3' 
                 ],
    [3] => array [
                   name => 'b',
                   service => 'x1' 
                 ],
    [4] => array [
                   name => 'b',
                   service => 'x3' 
                 ],
    [5] => array [
                   name => 'b',
                   service => 'x5' 
                 ]
]

我希望在一个元素和b中使用所有服务,以及如下所示:

array [
    [0] => array [
                   name => 'a',
                   service => 'x1, x2, x3' 
                 ],
    [1] => array [
                   name => 'b',
                   service => 'x1, x3, x5' 
                 ]
]

php代码:

$new_services = array(); 
foreach($services as $service) {
      if (isset($new_services[$service->name])) {
           $new_services[$service->name] .= $service['name'].',';
      }
      else{ 
         $new_services[$service->name] = $service['service'];
      }
}

预期结果与我想要的结果不一样。

1 个答案:

答案 0 :(得分:3)

这应该适合你:

只需遍历每个子数组并检查$result数组中是否有一个子数组,其名称为索引。如果不将其添加到结果数组中。如果您已拥有名称的密钥,只需将服务值附加到该密钥即可。最后,只需使用array_values()重新索引数组。

<?php

    $result = [];
    foreach($arr as $v) {
        if(!isset($result[$v["name"]])) {
            $result[$v["name"]]["name"] = $v["name"];
            $result[$v["name"]]["service"] = $v["service"];
        } else {
            $result[$v["name"]]["service"] .= ", " . $v["service"];
        }
    }

    $result = array_values($result);
    print_r($result);

?>

输出:

Array
(
    [0] => Array
        (
            [name] => a
            [service] => x1, x2, x3
        )

    [1] => Array
        (
            [name] => b
            [service] => x1, x3, x5
        )

)