简体   繁体   中英

Outputting array contents as nested list in PHP

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:

<ul>
  <li>
     <a href=""/>FIRST ELEMENT OF THE array ==> 1</a>
     <a href=""/>2ND ELEMENT OF THE TAB ==> 2</a>
     <a href=""/>3THIRD ELEMENT==> 3</a>
     <a href=""/>FORTH ELEMENT OF THE TAB ==> 4</a>
     <a href=""/>FIFTH ELEMENT==> 5</a>
 </li>
 <li>
     <a href=""/>6th ELEMENT==> 6</a>
     <a href=""/>7th ELEMENT OF THE TAB ==> 7</a>
     <a href=""/>8th ELEMENT==> 8</a>
     <a href=""/>9th ELEMENT OF THE TAB ==> 9</a>
     <a href=""/>10th ELEMENT OF THE TAB ==> 9</a>
 </li>


</ul>

How can I achieve this in PHP? I am thinking of creating a sub array with array_slice .

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

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>";

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

<?php
for($i = 0 ; $i < count($tab) ; $i += 2) {
    echo "<a href>" . $tab[$i] . "</a>";
    echo "<a href>" . $tab[$i+1] . "</a>";
}
?>

Like that.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM