1

重複の可能性:
PHP で多次元配列から重複した値を削除する方法

これを書くのが速すぎてすみません、私は仕事をしていました...、ごめんなさい。今、私はよく説明されていると思います.I want to remove subarrays with the subelement [title] common, equals, I want only one element, not repeats, how can I do it?. 私はそれを作りましたが、それを作るにはもっとエレガントな方法に違いないと思います. 私はこのコードで試しました:

static function remove_duplicates_titles($deals){
       $result = array();
       $deal_repeated=false;
       foreach ($deals as $index=>$deal) {
           foreach ($deals as $deal_2) {
               //discover if the subarray has the element title repeated is repeated or not
               if ($deal['title'] == $deal_2['title']){ 
                    $deal_repeated=true;
                    unset($deal_2);  
               }
               else{ 
                    $deal_repeated=false;                          
                }

           }
          //if the array has no the element (title) repeated with another....
          if(!$deal_repeated){
                   $result[]=$deal;
           }
       }

       return $result;

}

Array
(
[0] => Array
    (
        [id] => abc
        [title] => bbb
    )

[1] => Array
    (
        [id] => ghi
        [title] => aaa
    )

[2] => Array              //I should to remove this subarray (or the other, only one of both)
    (
        [id] => mno
        [title] => pql     //this is common
    )

[3] => Array
    (
        [id] => abc
        [title] => def
    )

[4] => Array
    (
        [id] => ghi
        [title] => mmm
    )

[5] => Array             //I should to remove this subarray (or the other), only one of both
    (
        [id] => mno
        [title] => pql   //this is common
    )

)

4

2 に答える 2

5

この関数は、見つかった FIRSTS 要素を保持し、指定したキーに基づいて重複を削除します

$arr = Array (
    Array ( 'id' => 'abc', 'title' => 'bbb' ),
    Array ( 'id' => 'ghi', 'title' => 'aaa' ),
    Array ( 'id' => 'mno', 'title' => 'pql' ),
    Array ( 'id' => 'abc', 'title' => 'def' ),
    Array ( 'id' => 'ghi', 'title' => 'mmm' ),
    Array ( 'id' => 'ere', 'title' => 'pql' )
);
function arrayUniqueFromKey(array $arr,$key)
{
    $titles = array();$ret = array();
    foreach ($arr as $v) {
        if (!in_array($v[$key],$titles)) {
            $titles[] = $v[$key];
            $ret[] = $v;
        }
    }
    return $ret;
}
print_r(arrayUniqueFromKey($arr,'title'));

http://codepad.org/Y3gsibRM

于 2012-10-22T13:00:44.163 に答える
1
    foreach($array as $key => $val) {
     if (is_array($val)) { 
      foreach($array as $key2 => $val2) {
       if($val['id']==$val2['id'] || $val['title']==$val2['title'])
       {
         unset($array[$key]);
         break;
       }
      }
    }
  }
于 2012-10-22T12:34:38.327 に答える