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:
-
<?php
for($i = 0 ; $i < count($tab) ; $i += 2) {
echo "<a href>" . $tab[$i] . "</a>";
echo "<a href>" . $tab[$i+1] . "</a>";
}
?>
Like that.
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
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>";
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>';
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>';