Skip to content

Instantly share code, notes, and snippets.

@ajshort
Created August 15, 2011 07:57
Show Gist options
  • Select an option

  • Save ajshort/1145877 to your computer and use it in GitHub Desktop.

Select an option

Save ajshort/1145877 to your computer and use it in GitHub Desktop.
<?php
/**
* A list decorator that allows a list to be grouped into sub-lists by common
* values of a field.
*
* @package sapphire
* @subpackage model
*/
class GroupedList extends SS_ListDecorator {
/**
* @param string $index
* @return ArrayList
*/
public function groupBy($index) {
$result = array();
foreach ($this->list as $item) {
$key = is_object($item) ? $item->$index : $item[$index];
if (array_key_exists($key, $result)) {
$result[$key]->push($item);
} else {
$result[$key] = new ArrayList(array($item));
}
}
return $result;
}
/**
* @param string $index
* @param string $children
* @return ArrayList
*/
public function GroupedBy($index, $children = 'Children') {
$grouped = $this->groupBy($index);
$result = new ArrayList();
foreach ($grouped as $index => $list) {
$result->push(new ArrayList(array(
$index => $index,
$children => $list
)));
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment