2015-05-27 198 views
1

我有这个PHP数组合并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' 
       ] 
] 

我想marage全部的服务中的一个元素是什么和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']; 
     } 
} 

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

+0

凡在你尝试,如果两个项目具有相同的名称,你检查?你是如何期望PHP知道你想要的? – IMSoP

+0

那么,我们这个问题在哪里? – Rizier123

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

)