Last active
March 6, 2019 17:12
-
-
Save telmott/9a1f57e5691645a634ed4e92058c6f2d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
/** | |
* 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 <[email protected]> | |
*/ | |
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