简体   繁体   中英

multidimensional array duplicates merge

I have a multidimensional array and i want to combine duplicates with the same data, for example i have an array with this fields:

    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"
  }
  }

And i want to combine the same dates in one.

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"
  }
  }

How do I do this? Thanks

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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