Tree.php 736 B

123456789101112131415161718192021222324252627282930313233
  1. <?php
  2. namespace app\helpers;
  3. use yii\helpers\ArrayHelper;
  4. class Tree
  5. {
  6. public static function buildTree(array $elements, $parentId = 0) {
  7. $branch = array();
  8. foreach ($elements as $element) {
  9. if ($element['parent_id'] == $parentId) {
  10. $children =self::buildTree($elements, $element['id']);
  11. if ($children) {
  12. $element['children'] = $children;
  13. }
  14. $branch[] = $element;
  15. }
  16. }
  17. return $branch;
  18. }
  19. public static function drawTree( $items, $draw, $lavel = 0 ){
  20. foreach( $items as $item ){
  21. echo $draw->render('_item', [
  22. 'model' => $item['item'], 'lavel' => $lavel
  23. ]);
  24. if( isset( $item['children'] ) && $item['children'] ){
  25. self::drawTree( $item['children'], $draw, $lavel+1 );
  26. }
  27. }
  28. }
  29. }