Skip to content

Instantly share code, notes, and snippets.

@kazeno
Last active September 13, 2016 13:02
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/643ba041093c3c2f7b0627c203089fdf to your computer and use it in GitHub Desktop.
Save kazeno/643ba041093c3c2f7b0627c203089fdf to your computer and use it in GitHub Desktop.
Sort objects hierarchically in recursive multidimensional arrays
<?php
$entries = yourGetEntriesFromDbFunction(); //The array with our retrieved DB entries
$entryRecords = array(); //Our hierarchy will be created in this array
//We will track the path of each entry here, with an array
//for each entry containing the ids of all its ancestors:
$entryPaths = array();
foreach ($entries as $entry) {
//Create a new key inside each entry to store its children:
$entry['children'] = array();
$entryPaths[$entry['id']] = array(); //Make a space for the path of the entry
if ($entry['parent'] === NULL) { //If top level, just insert into the hierarchy array
$entryRecords[$entry['id']] = $entry;
} else {
$pathRef =& $entryRecords; //Save a reference to the top level of our hierarchy
//Traverse our current hierarchy based on the path of the entry's parent by reassigning a
//single variable by reference to the children container of each level in the hierarchy:
foreach ($entryPaths[$entry['parent']] as $path) {
$pathRef =& $pathRef[$path]['children'];
}
//Once we reach the entry's parent's children container, just add the entry to it:
$pathRef[] = $entry;
//Register the entry's path by first copying parent's path
$entryPaths[$entry['id']] = $entryPaths[$entry['parent']];
}
$entryPaths[$entry['id']][] = $entry['id']; //Finally add the id of the entry to its path
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment