Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

下記のように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) "新宿"
  }
}
Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away