Last active
September 20, 2017 23:30
-
-
Save wpscholar/1372678 to your computer and use it in GitHub Desktop.
Take a multi-dimensional array in $_POST format and convert into an unordered list.
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 | |
/** | |
* | |
* Take a multi-dimensional array in $_POST format and convert into an unordered list. | |
* | |
* @param $data | |
* @param array $args | |
* @return string | |
*/ | |
function generate_list( $data, $args = array() ){ | |
// Set internal loop counter | |
$loop = ( isset( $args['loop'] ) && is_int( $args['loop'] ) ) ? (int) $args['loop']: 0; | |
// Make recursive only to the desired depth | |
$depth = ( isset( $args['depth'] ) && is_int( $args['depth'] ) ) ? (int) $args['depth']: 0; | |
// Set current depth | |
$loop++; | |
// Determine list type | |
$list = ( isset( $args['list'] ) && $args['list'] == 'ol' ) ? 'ol': 'ul'; | |
// Get and set classes | |
$parent_classes = !empty($args['parent_class']) ? (array) $args['parent_class']: array(); | |
$child_classes = !empty($args['child_class']) ? (array) $args['child_class']: array(); | |
$classes = ( $loop == 1 ) ? $parent_classes: array_merge( $parent_classes, $child_classes ); | |
$classes = empty( $classes ) ? '': ' classes="'.str_replace('#', $loop, join(' ', $classes) ).'"'; | |
// Unset parent class | |
unset( $args['parent_class'] ); | |
// HTML list generation | |
$html = array(); | |
$next = false; | |
if( $depth == 0 || $depth >= $loop ){ | |
$html[] = '<'.$list.$classes.'>'; | |
foreach( $data as $k => $v ){ | |
$next = next( $data ); | |
if( is_array( $v ) ){ | |
$args['loop'] = $loop; | |
$args['depth'] = $depth; | |
$html[] = call_user_func(__FUNCTION__, $v, $args ); | |
} else { | |
if( $next && is_array( $next ) ){ | |
$html[] = '<li>'.$v; | |
} else { | |
$html[] = '<li>'.$v.'</li>'; | |
} | |
} | |
} | |
$html[] = '</'.$list.'>'; | |
} | |
if( !$next && $loop > 1 ){ | |
$html[] = '</li>'; | |
} | |
return implode( $html ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment