Skip to content

Instantly share code, notes, and snippets.

@kazeno
Created September 13, 2016 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kazeno/91b9e5e3708847729a8270b0c62c6f3d to your computer and use it in GitHub Desktop.
Save kazeno/91b9e5e3708847729a8270b0c62c6f3d to your computer and use it in GitHub Desktop.
Sort objects hierarchically in recursive multidimensional arrays in Yii
<?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