Jump to content

Populate PHP multidimensional array and add the attributes to the category heading


bobtutos

Recommended Posts

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
Math

I 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


<?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>';

?>

  • Like 1
Link to comment
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...