From php multidimensional array get html ul li ul li... with less loops (using less system resources) -
have php array
array ( [0] => array ( [numberrenamed] => 2 [topicname] => contacts [upperlevelnumberrenamed] => 0 ) [1] => array ( [numberrenamed] => 3 [topicname] => legal services [upperlevelnumberrenamed] => 1 ) [2] => array ( [numberrenamed] => 1 [topicname] => services [upperlevelnumberrenamed] => 0 ) [3] => array ( [numberrenamed] => 4 [topicname] => accounting services [upperlevelnumberrenamed] => 1 ) )
from array want html this
<div> <ul class="mnav-ul"> <li class="mnav-ul-li">contacts</li> <li class="mnav-ul-li">services <ul class="mnav-ul-ul"> <li>legal services</li> <li>accounting services</li> </ul> </li> </ul> </div> <div style="clear:both"></div>
i did
1) created 1 array of top level menu items, array sub level menu(s) items , array contains upperlevelnumberrenamed
of sub level menu(s) items
foreach ( $navigation $k_navigation => $v_navigation ){ if( $v_navigation['upperlevelnumberrenamed'] == 0 ){ $top_level_navigation[] = $v_navigation; } else if( $v_navigation['upperlevelnumberrenamed'] != 0 ){ $sub_level_navigation[] = $v_navigation; $sublev_upper_level_number_renamed[] = $v_navigation['upperlevelnumberrenamed']; }//else if( $v_navigation['upperlevelnumberrenamed'] != 0 ){ }//foreach ( $navigation $k_navigation => $v_navigation ){
2) loop @ first through top level items array , inside each loop again loop through sub level menu(s) items
$main_navigation = ' <div> <ul class="mnav-ul"> '; foreach ( $top_level_navigation $k_top_level_navigation => $v_top_level_navigation ){ if( !in_array( $v_top_level_navigation['numberrenamed'], $sublev_upper_level_number_renamed ) ) { $main_navigation .= '<li class="mnav-ul-li">'. $v_top_level_navigation['topicname']. '</li>'; } else if( in_array( $v_top_level_navigation['numberrenamed'], $sublev_upper_level_number_renamed ) ) { $main_navigation .= '<li class="mnav-ul-li">'. $v_top_level_navigation['topicname']. ''; $main_navigation .= '<ul class="mnav-ul-ul">'; foreach ( $sub_level_navigation $k_sub_level_navigation => $v_sub_level_navigation ){ if( $v_top_level_navigation['numberrenamed'] == $v_sub_level_navigation['upperlevelnumberrenamed'] ){ $main_navigation .= '<li>'. $v_sub_level_navigation['topicname']. '</li>'; } }//foreach ( $sub_level_navigation $k_sub_level_navigation => $v_sub_level_navigation ){ $main_navigation .= '</ul></li>'; }//if( ( in_array( $v_top_level_navigation['numberrenamed'], $sublev_upper_level_number_renamed ) ) { }//foreach ( $navigation $k_navigation => $v_navigation ){ $main_navigation .= '</ul> </div> <div style="clear:both"></div>'; echo $main_navigation;
can need. many loops (possible waste of system resources). possible same result less loops (using less system resurces)?
Comments
Post a Comment