Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

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,
[]
]
]
]
]
]
]

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

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.

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