55
51

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

連想配列中の重複したレコードを削除する

Last updated at Posted at 2015-01-14

下記のようにDBから取ってきたデータを連想配列にして、重複したレコードを削除したいときってよくある。

$stations = [ 
   ['id' => 1, 'name' => '恵比寿'],
   ['id' => 2, 'name' => '渋谷'],
   ['id' => 3, 'name' => '新宿'],
   ['id' => 4, 'name' => '恵比寿'],
];

ここから恵比寿を削除した3つの配列にするためのメモ。

$tmp = [];
$uniqueStations = [];
foreach ($stations as $station){
   if (!in_array($station['name'], $tmp)) {
      $tmp[] = $station['name'];
      $uniqueStations[] = $station;
   }
}

メソッド化しておいても良いレベルかも。


class Util {
   public static function getUniqueArray($array, $column)
   {   
      $tmp = []; 
      $uniqueArray = []; 
      foreach ($array as $value){
         if (!in_array($value[$column], $tmp)) {
            $tmp[] = $value[$column];
            $uniqueArray[] = $value;
         }   
      }   
      return $uniqueArray;    
   }   
}

$stations = Util::getUniqueArray($stations, 'name');
echo("<pre>");var_dump($stations);echo("<pre>");

結果がこちら。


array(3) {
  [0]=>
  array(2) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(9) "恵比寿"
  }
  [1]=>
  array(2) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(6) "渋谷"
  }
  [2]=>
  array(2) {
    ["id"]=>
    int(3)
    ["name"]=>
    string(6) "新宿"
  }
}
55
51
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
55
51

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?