[ 'id' => '00000000-0000-0000-0000-000000000000', 'name' => TTi18n::getText( 'Root' ), 'level' => 0, 'children' => $nodes, ], ]; } return $nodes; } /** * Flatten a nested array. * @param $nodes * @return array */ static function flattenArray( $nodes ) { $retarr = []; foreach ( $nodes as $key => $node ) { if ( isset( $node['children'] ) ) { $retarr = array_merge( $retarr, self::flattenArray( $node['children'] ) ); unset( $node['children'] ); $retarr[] = $node; } else { $retarr[] = $node; } } return $retarr; } /** * Get one specific element from all nodes in nested array. * @param $nodes * @param string $key * @return array */ static function getElementFromNodes( $nodes, $key = 'id' ) { $retarr = []; if ( is_array( $nodes ) ) { foreach ( $nodes as $node ) { $retarr[] = $node[$key]; if ( isset( $node['children'] ) ) { $retarr[] = self::getElementFromNodes( $node['children'] ); } } } return $retarr; } /** * Get just the children of a specific parent. * @param $nodes * @param string $parent_id * @return array */ static function getAllChildren( $nodes, $parent_id = '00000000-0000-0000-0000-000000000000' ) { $nodes = self::createNestedArrayWithDepth( $nodes, $parent_id ); return $nodes; } /** * @param $a * @param $b * @return int */ static function sortByName( $a, $b ) { if ( $a['name'] == $b['name'] ) { return 0; } return ( $a['name'] < $b['name'] ) ? -1 : 1; } /** * Takes a flat array of nodes typically straight from the database and converts into a nested array with depth/level values. * @param $nodes * @param string $parent_id * @param int $depth * @return array */ static function createNestedArrayWithDepth( $nodes, $parent_id = '00000000-0000-0000-0000-000000000000', $depth = 1 ) { $retarr = []; if ( is_array( $nodes ) ) { uasort( $nodes, [ 'self', 'sortByName' ] ); foreach ( $nodes as $element ) { $element['level'] = $depth; if ( isset( $element['parent_id'] ) && isset( $element['id'] ) && $element['parent_id'] == $parent_id ) { $children = self::createNestedArrayWithDepth( $nodes, $element['id'], ( $depth + 1 ) ); if ( $children ) { uasort( $children, [ 'self', 'sortByName' ] ); $element['children'] = $children; } $retarr[] = $element; } } } return $retarr; } } ?>