Mark Alan Mark Alan - 5 months ago 10
PHP Question

Spliting up array values into 3

I have stored navigation menu into the database and wanted to break into 3 columns col-md-3 like every 3 li will be wraped into col-md-3 let me show you it is made statically

<div class="col-sm-3">
<ul>
<li><a href="">Careers</a></li>
<li><a href="">Services</a></li>
<li><a href="">Make a Booking</a></li>
</ul>
</div>

<div class="col-sm-3">
<ul>
<li><a href="">Find a Store</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Contact us</a></li>
</ul>
</div>
<div class="col-sm-3">
<ul>
<li><a href="">Terms and Conditions</a></li>
<li><a href="">Privacy Policy</a></li>
<li><a href="">Delivery and Returns</a></li>
</ul>
</div>


And all these navigation menu is in the database how do i make them dynamic I tried using for loop but not working using it

<?php
$nav = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '');
$total = count($nav);
$i = 1;

for($i; $i <= $total; $i++) {
$ans = $i / 3;
?>
<?php if(round($ans) == 3) { ?>
<div class="col-sm-3">
<ul>
<?php for($j = 1; $j <= $ans; $j++) { ?>
<li><a href=""><?php echo $nav[$j]; ?></a></li>
<?php } ?>
</ul>
</div>
<?php } ?>

<?php if($i == 1) { ?>
<div class="col-sm-3">
<ul>
<?php for($k = 0; $k <= $ans; $k++) { ?>
<li><a href=""><?php echo $nav[$k]; ?></a></li>
<?php } ?>
</ul>
</div>
<?php } ?>

<?php } ?>


I tried using simple test using custom array values but this is not happenign what should I do in order

Answer

Try this:

<?php 
$nav = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', '');
$total = count($nav);
$i     = 0;
foreach($nav as $sub) {
if($i % 3 == 0) {
  if($i != 0) { ?> </ul></div><?php }
?>
<div class="col-sm-3">
    <ul>
<?php } ?>
        <li><a href=""><?php echo $sub; ?></a></li>

<?php $i++; 
} 
?>

Output:

  • a
  • b
  • c


  • d
  • e
  • f


  • g
  • h
  • i

Comments