mirror of
https://github.com/silverstripe/silverstripe-framework
synced 2024-10-22 14:05:37 +02:00
ENHANCEMENT: Added ArrayList->removeDuplicates().
This commit is contained in:
parent
99a2baf3f8
commit
462689a4e6
@ -90,6 +90,26 @@ class ArrayList extends ViewableData implements SS_List {
|
||||
foreach ($with as $item) $this->push($item);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes items from this list which have a duplicate value for a certain
|
||||
* field. This is especially useful when combining lists.
|
||||
*
|
||||
* @param string $field
|
||||
*/
|
||||
public function removeDuplicates($field = 'ID') {
|
||||
$seen = array();
|
||||
|
||||
foreach ($this->array as $key => $item) {
|
||||
$value = $this->extract($item, $field);
|
||||
|
||||
if (array_key_exists($value, $seen)) {
|
||||
unset($this->array[$key]);
|
||||
}
|
||||
|
||||
$seen[$value] = true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushes an item onto the end of this list.
|
||||
*
|
||||
|
@ -90,6 +90,25 @@ class ArrayListTest extends SapphireTest {
|
||||
));
|
||||
}
|
||||
|
||||
public function testRemoveDuplicates() {
|
||||
$list = new ArrayList(array(
|
||||
array('ID' => 1, 'Field' => 1),
|
||||
array('ID' => 2, 'Field' => 2),
|
||||
array('ID' => 3, 'Field' => 3),
|
||||
array('ID' => 4, 'Field' => 1),
|
||||
(object) array('ID' => 5, 'Field' => 2)
|
||||
));
|
||||
|
||||
$this->assertEquals(5, count($list));
|
||||
$list->removeDuplicates();
|
||||
$this->assertEquals(5, count($list));
|
||||
|
||||
$list->removeDuplicates('Field');
|
||||
$this->assertEquals(3, count($list));
|
||||
$this->assertEquals(array(1, 2, 3), $list->column('Field'));
|
||||
$this->assertEquals(array(1, 2, 3), $list->column('ID'));
|
||||
}
|
||||
|
||||
public function testPushPop() {
|
||||
$list = new ArrayList(array('Num' => 1));
|
||||
$this->assertEquals(1, count($list));
|
||||
|
Loading…
Reference in New Issue
Block a user