Listing the contents of an array as a nested list in PHP

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

<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 helper array with array_slice.

+3
source share
5 answers

to 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>";
+1
source

Updated to reflect 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>';
+6
source

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

?>

Tooltip explanation: $ i% n (mod) is 0 when $ i is an element of nTh (remainder of division is 0)

EDITED: made a general decision

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

Like this.

0
source

try the following:

$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
source

Source: https://habr.com/ru/post/1784541/


All Articles