Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Class to sort items.

Copyright: 2019 Ryan Wyllie <ryan@moodle.com>
License: http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
File Size: 152 lines (5 kb)
Included or required:0 times
Referenced: 0 times
Includes or requires: 0 files

Defines 1 class

sorter:: (3 methods):
  __construct()
  sort_into_children()
  flatten_children()


Class: sorter  - X-Ref

Class to sort lists of items.

__construct(callable $getid, callable $getparentid)   X-Ref
Constructor.

Allows the calling code to provide 2 functions to get the id and parent id from
the list of items it is intended to process.

This allows this class to be composed in numerous different ways to support various
types of items while keeping the underlying sorting algorithm consistent.

param: callable $getid Function used to get the id from an item
param: callable $getparentid Function used to get the parent id from an item

sort_into_children(array $items)   X-Ref
Sort a list of items into a parent/child data structure. The resulting data structure
is a recursive array of arrays where the first element is the parent and the second is
an array of it's children.

For example
If we have an array of items A, B, C, and D where D is a child of C, B and C are children
of A.

This function would sort them into the following:
[
[
A,
[
[
B,
[]
],
[
C,
[
[
D,
[]
]
]
]
]
]
]

param: array $items The list of items to sort.
return: array

flatten_children(array $items)   X-Ref
Take the data structure returned from "sort_into_children" and flatten it back
into an array. It does a depth first flatten which maintains the reply ordering.

param: array $items Items in the data structure returned by "sort_into_children"
return: array A flat array.