bobtutos Posted September 25, 2016 Share Posted September 25, 2016 how to populate PHP multidimensional array and add the attributes to the category heading nodes,I have the following Books array$book = array( "language"=> array("English","Franch","Arabic"), "Programming"=> array("PHP","JAVA","C++"), "Science"=> array("Physics","Geography","Math"),); function treeView($book){ $markUp = ""; foreach($book as $cate => $subj){ $markUp .= "<li>".((is_array($subj))?$cate.treeView($subj):$subj)."</li>"; } return "<ul>$markUp</ul>"; } treeView($book); //------------------- The result is what I expected language English Franch Arabic Programming PHP JAVA C++ Science Physics Geography MathI want to do the following (adding class)<ul> <li class="language">language <ul> <li>English</li> <li>Franch</li> <li>Arabic</li> </ul> </li> <li class="Programming">Programming <ul> <li>PHP</li> <li>JAVA</li> <li>C++</li> </ul> </li> <li class="Science">Science <ul> <li>Physics</li> <li>Geography</li> <li>Math</li> </ul> </li></ul> Your help is highly appreciated Thank you. Link to comment Share on other sites More sharing options...
dsonesuk Posted September 25, 2016 Share Posted September 25, 2016 <?php $book = array( "Language" => array("English", "Franch", "Arabic"), "Programming" => array("PHP", "JAVA", "C++"), "Science" => array("Physics", "Geography", "Math"), ); $classRef = ""; $keysvalues = array_keys($book); echo '<ul>'; for ($i = 0; $i < sizeof($book); $i++) { $classRef = str_replace(" ", "_", strtolower($keysvalues [$i])); echo '<li class="' . $classRef . '">' . $keysvalues [$i]; echo '<ul>'; foreach ($book[$keysvalues [$i]] as $value) { echo '<li>' . $value . "</li>"; } echo '</ul>'; echo "</li>"; } echo '</ul>'; ?> 1 Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now