[PHP] 二次元配列の重複項目を削除

2006年11月28日 火曜日 22時11分
E-Mail This Post/Page Print This Post/Page

array_unique関数を使用して、一次元配列の重複項目を削除することができますが、では二次元配列の場合はどうするのでしょうか。マニュアルのユーザーノートに便利なカスタム関数がアップされているので使用してみたのですが、かなり使いやすかったので紹介します。

MoD氏の投稿を参照。

function remove_duplicate($array, $field)
{
  foreach ($array as $sub)
   $cmp[] = $sub[$field];
  $unique = array_unique($cmp);
  foreach ($unique as $k => $rien)
   $new[] = $array[$k];
  return $new;
}

$field に、エレメントのインデックス名を記入します。使用例としては、

$arr = array(
        array( 'title' => 'test01', 'date' => '2006-11-24', 'description' => 'this is a test' ),
        array( 'title' => 'test02', 'date' => '2006-11-25', 'description' => 'this is another test' ),
        array( 'title' => 'test03', 'date' => '2006-11-26', 'description' => 'this is a test' ),
        array( 'title' => 'test01', 'date' => '2006-11-27', 'description' => 'this is a testthis is a different test' )
      );

という二次元配列があったとします。この配列はそれぞれ $arr[0][’title’] と $arr[3][’title’] 、$arr[0][’description’] と $arr[2][’description’] が重複しています。これを上の関数を使用してひとつにまとめてみます。
 

$arr = remove_duplicate($arr, 'title');

で [’title’] の重複項目が削除され、結果、

Array (
       [0] => Array ( [title] => test01 [date] => 2006-11-24 [description] => this is a test )
       [1] => Array ( [title] => test02 [date] => 2006-11-25 [description] => this is another test )
       [2] => Array ( [title] => test03 [date] => 2006-11-26 [description] => this is a test )
       )

また、

$arr = remove_duplicate($arr, 'description');

で [’description’] 下の重複項目が削除されます。結果は以下のようになります。

Array ( [0] => Array ( [title] => test01 [date] => 2006-11-24 [description] => this is a test )
        [1] => Array ( [title] => test02 [date] => 2006-11-25 [description] => this is another test )
        [2] => Array ( [title] => test01 [date] => 2006-11-27 [description] => this is a testthis is a different test )
       )

この記事に関連する NEWS

この記事に関連するトピック

このエントリーへの Yahoogle Suggestions

Trackback this Post |

 

記事ヒット TOP 10

IT 関連 NEWS

    There is no entries available for this category.

PHP関連 NEWS

    There is no entries available for this category.

PHP Tips from Social Bookmarks

    There is no entries available for this category.

PHPに関するフォーラムトピック

    There is no entries available for this category.

Tag Cloud

admin Admin Drop Menus Admin Memo Admin Panel advanced drop menus array unique blog cron dabeya Dagon Design Sitemap Generator dropcap Edit N Place error Feedburner game google hack html HTML CSS Internet NEWS Permalink Redirect PHP phpBB2 plugin RSS scripts search stattraq template the content Ultimate Tag Warrior Web Management Windows XP Wordpress WP Plugins WPページ  拡張子 カスタマイズ カスタム関数 カテゴリー コード セキュリティ タグ トップページ トラックバック フィード 投稿 抜粋 日本語 時刻 時間 正規表現 表示 記事

サイト メニュー

Blogtimes image
ぱそずき :D)‐く © 2008
Close
E-mail It