Created
August 15, 2011 07:57
-
-
Save ajshort/1145877 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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