多维数组重复合并

时间:2013-07-23 20:15:29

标签: php arrays multidimensional-array merge

我有一个多维数组,我想将重复项与相同的数据组合起来,例如 我有一个包含这个字段的数组:

    array(5) {
  [0]=>
  array(2) {
    ["data"]=> string(10) "05-30-2013"
    ["link"]=> string() "unions"
  }
  [1]=>
  array(2) {
    ["data"]=> string(10) "06-03-2013"
    ["link"]=> string() "potatoes"
  }
  [2]=>
  array(2) {
    ["data"]=> string(10) "06-03-2013"
    ["link"]=> string() "apple"
  }
  [3]=>
  array(2) {
    ["data"]=> string(10) "06-03-2013"
    ["link"]=> string() "banana"
  }
  [4]=>
  array(2) {
    ["data"]=> string(10) "05-30-2013"
    ["link"]=> string() "pear"
  }
  }

我希望将相同的日期合二为一。

array(2) {
  [0]=>
  array(2) {
    ["data"]=> string(10) "05-30-2013"
    ["link"]=> string() "unions,pear"
  }
  [1]=>
  array(2) {
    ["data"]=> string(10) "06-03-2013"
    ["link"]=> string() "potatoes,apple,banana"
  }
  }

我该怎么做? 感谢

1 个答案:

答案 0 :(得分:3)

$arr = array (
   0 => array (
     "data" => "05-30-2013",
     "link" => "unions"),
   1 => array (
     "data" => "06-03-2013",
     "link" => "potatoes"),
   2 => array (
     "data" => "06-03-2013",
     "link" => "apple"),
   3 => array (
     "data" => "06-03-2013",
     "link" => "banana"),
   4 => array (
     "data" => "05-30-2013",
     "link" => "pear"));
$out = array();
foreach ($arr as $key => $value){
    if (array_key_exists($value['data'], $out)){
        $out[$value['data']]['link'] .= ', '.$value['link'];
    } else {
        $out[$value['data']] = array('data' => $value['data'], 'link' => $value['link']);
    }
}
$out = array_values($out);
print_r($out);