ぶろぐ

日記です

PHPで重複したデータ取り除きたい


軽くググッた感じだと、データクラス(いつも呼び方に悩む)の重複を取り除く関数とかはさすがにないっぽい。

<?php

class HogeEntity {
	private $id;
	private $text;
	function __construct($id, $text) {
			$this->id   = $id;
			$this->text = $text;
	}
	function getId() { return $this->id; }
	function setId($id) { $this->id = $id; }
	function getText() { return $this->text; }
	function setText($text) { $this->text = $text; }
}

// 重複したデータ
$src_hoges[] = new HogeEntity(1, "hoge");
$src_hoges[] = new HogeEntity(3, "nya-");
$src_hoges[] = new HogeEntity(1, "hoge");

$hoge_ids = array();	// 記憶用
$hoges = array();		// 結果用
foreach($src_hoges as $h) {
    if(!in_array($h->getId(), $hoge_ids)) {
        $hoge_ids[] = $h->getId();
		$hoges[] = $h;
    }
}
<?php
/* まぁほんとはこんなの作るべきだった。 */
class ArrayUtil {
	/** Trim Duplicate Object */
	static public function trimDuplicate($src, $key) {
		// getter method
		$getKey = sprintf('get%s', ucfirst($key));
		$dst = array();
		$ids = array();
		foreach($src as $s) {
    		if(!in_array($s->$getKey(), $ids)) {
    		    $ids[] = $s->getId();
				$dst[] = $s;
			}
		}
		return $dst;
	}
}

$trim_hoges = ArrayUtil::trimDuplicate($src_hoges, 'id');

var_dump($trimHoge);
//array(2) {
//  [0]=>
//  object(HogeEntity)#1 (2) {
//    ["id":"HogeEntity":private]=>
//    int(1)
//    ["text":"HogeEntity":private]=>
//    string(4) "hoge"
//  }
//  [1]=>
//  object(HogeEntity)#2 (2) {
//    ["id":"HogeEntity":private]=>
//    int(3)
//    ["text":"HogeEntity":private]=>
//    string(4) "nya-"
//  }
//}