Skip to content

Instantly share code, notes, and snippets.

@telmott
Last active March 6, 2019 17:12
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 telmott/9a1f57e5691645a634ed4e92058c6f2d to your computer and use it in GitHub Desktop.
Save telmott/9a1f57e5691645a634ed4e92058c6f2d to your computer and use it in GitHub Desktop.
<?php
/**
* Oder Term list by hierarchy.
*
* @param array $terms Array of terms to be hierarchical sorted
* @return array $ordered_terms Array ot terms orderd by parent->child relation
* @author Telmo Teixeira <telmo@widgilabs.com>
*/
function ( array $terms ) {
// Start by matching the terms array.
$ordered_terms = $terms;
$loop_max = count( $ordered_terms ) - 1;
// The outer loop iterates one time foreach item of the array.
for ( $x = 0; $x < $loop_max; $x++ ) {
// keep record of how many ordered items we found in the current iteration.
$found = 0;
// The inner loop modifies the array order.
for ( $i = $loop_max; $i > 0; $i-- ) {
$curr = $ordered_terms[ $i ];
$prev = $ordered_terms[ $i - 1 ];
/**
* If the current item is not previous's child they change places.
* This forces every item to travel through the array until it finds
* it's parent, then it stops.
*/
if ( $curr->parent !== $prev->term_id ) {
// Remove from array.
array_splice( $ordered_terms, ( $i - 1 ), 1 );
// Insert after last ordered item (current + found).
array_splice( $ordered_terms, ( $i + $found ), 0, array( $prev ) );
} else {
// +1 already in place found.
$found++;
}
}
}
return $ordered_terms;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment