Created
September 13, 2016 13:08
-
-
Save kazeno/91b9e5e3708847729a8270b0c62c6f3d to your computer and use it in GitHub Desktop.
Sort objects hierarchically in recursive multidimensional arrays in Yii
This file contains 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 | |
$sections = Section::model()->findAll( | |
array('order'=>'parent ASC NULLS FIRST,"order"')); //PostgreSQL FTW | |
$entryRecords = array(); | |
$entryPaths = array(); | |
foreach ($sections as $section) { | |
$section->children = array(); | |
$entryPaths[$section->id] = array(); | |
if ($section->parent === NULL) { | |
$entryRecords[$section->order] = $section; | |
} else { | |
$pathRef =& $entryRecords; | |
foreach ($entryPaths[$section->parent] as $path) { | |
$pathRef =& $pathRef[$path]->children; | |
} | |
$pathRef[] = $section; | |
$entryPaths[$section->id] = $entryPaths[$section->parent]; | |
} | |
$entryPaths[$section->id][] = $section->order; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment