Outputting array contents as nested list in PHP

后端 未结 5 1770
谎友^
谎友^ 2021-01-20 08:49

I have the array array ( [0] => array(1,2,3,4,5) [1] => array(6,7,8,9,10)) and I would like to display it like this:

相关标签:
5条回答
  • 2021-01-20 09:22
    <?php
    for($i = 0 ; $i < count($tab) ; $i += 2) {
        echo "<a href>" . $tab[$i] . "</a>";
        echo "<a href>" . $tab[$i+1] . "</a>";
    }
    ?>
    

    Like that.

    0 讨论(0)
  • 2021-01-20 09:25

    Here is another way to do this (demo here):

    <?php
    $tab = array(1,2,3,4,5,6,7,8,9,10);
    
    //how many <a> elements per <li>
    $aElements = 2;    
    
    $totalElems = count($tab);    
    
    //open the list
    echo "<ul><li>";
    
    for($i=0;$i<$totalElems;$i++){
    
        if($i != 0 && ($i%$aElements) == 0){ //check if I'm in the nTh element.
            echo "</li><li>"; //if so, close curr <li> and open another <li> element
        }
    
        //print <a> elem inside the <li>
        echo "<a href =''>".$tab[$i]."</a>";
    }
    
    //close the list
    echo "</li></ul>";
    
    ?>
    

    Tip explanation: $i%n (mod) equals 0 when $i is the nTh element (remainder of division is 0)

    EDITED: made a general solution

    0 讨论(0)
  • 2021-01-20 09:27

    try

    echo "<ul>";
    $i=0;
    $theCount = count($tab);
    while($i<$theCount){
        echo "<li>";
        echo "  <a href=""/>FIRST ELEMENT OF THE TAB ==> {$tab[$i]}</a>";
        $i++;
        echo "  <a href=""/>FIRST ELEMENT OF THE TAB ==> {$tab[$i]}</a>";
        echo "</li>";
        $i++;
    }
    echo "</ul>";
    
    0 讨论(0)
  • 2021-01-20 09:42

    try this:

    $sections = array_chunk(array(1,2,3,4,5,6,7,8,9,10), 2);
    
    echo '<ul>';
    
    foreach($sections as $value)
    {
     echo '<li>';
     echo '<a href=""/>'.$value[0].' ELEMENT OF THE TAB ==>  '.$value[0].'</a>';
     echo '<a href=""/>'.$value[1].' ELEMENT OF THE TAB ==>  '.$value[1].'</a>';
     echo '</li>';
    }
    
    echo '</ul>';
    
    0 讨论(0)
  • 2021-01-20 09:43

    Updated to take into account your actual array structure

    Your solution is a simple nested foreach.

    $tab = array(array(1,2,3,4,5), array(6,7,8,9,10));
    echo '<ul>';
    foreach ($tab as $chunks) {
        echo '<li>';
        foreach($chunks as $chunk) {
            echo '<a href="">' . $chunk . '</a>';
        }
        echo '</li>';
    }
    echo '</ul>';
    
    0 讨论(0)
提交回复
热议问题