zkanoca
zkanoca

Reputation: 9928

How to list key-value associative array using foreach

Assume that we have an array:

$aa = array('student1'=>array(1,2,3),'student2'=>array(3,2,4),'student3'=>array(4,3,5));

I want to have an HTML output like the following:

<ul>
    <li>student1
        <ul>
            <li>1</li>
            <li>1</li>
            <li>1</li>
        </ul>
    </li>
    <li>student2
        <ul>
            <li>3</li>
            <li>2</li>
            <li>4</li>
        </ul>
    </li>
    <li>student3
        <ul>
            <li>4</li>
            <li>3</li>
            <li>5</li>
        </ul>
    </li>
</ul>

But all I could do is

<ul>
    <li>
        <ul>
            <li>1</li>
            <li>1</li>
            <li>1</li>
        </ul>
    </li>
    <li> 
        <ul>
            <li>3</li>
            <li>2</li>
            <li>4</li>
        </ul>
    </li>
    <li> 
        <ul>
            <li>4</li>
            <li>3</li>
            <li>5</li>
        </ul>
    </li>
</ul>

In other words, I was not able to print keys for each inner array. How to do that?

I have coded something like that:

echo '<ul>';

foreach($aa as $a)
{
    echo '<li>' . /*Here it should be written the current student name*/ '<ul>';

    foreach($a as $b)
    {
        echo '<li>' . $b . '</li>';
    }
    echo '</ul></li>';

}
echo '</ul>';

Upvotes: 0

Views: 620

Answers (2)

Sean Bright
Sean Bright

Reputation: 120684

<ul>
<?php
  foreach ($aa as $name => $values) {
    echo "<li>$name\n";
    echo "<ul>\n";
    foreach ($values as $value) {
      echo "<li>$value</li>\n";
    }
    echo "</ul>\n";
    echo "</li>\n";
  }
?>
</ul>

Upvotes: 4

user3761550
user3761550

Reputation: 33

Print the array like this:

echo "<pre>";
print_r($array);
echo "</pre>";

This way you look at the internal structure of the array.

Then you can list it like this:

$a = array(
    "one" => 1,
    "two" => 2,
    "three" => 3,
    "seventeen" => 17
);

foreach ($a as $k => $v) {
    echo "\$a[$k] => $v.\n";
}

Upvotes: 0

Related Questions