Jump to content

Scroll through an array based on a 3 digit based variable


Recommended Posts

$array = array(5 => "001", 2 => "001001", 1 => "001001001", 9 => "002", 7 => "002001");

 

Each 3 digits mean a new level or sub level (e.g. XXX, XXXYYY, XXXYYYZZZ, etc.).

 

What I want is to have this printed:

<ul class="level">

<li>5</li>
<ul class="level">
<li>2</li>
<ul class="level">
<li>1</li>
</ul>
</ul>
<li>2
<ul class="level">
<li>7</il>
</ul>

</ul>

As <ul class="level"> adds another visual level, it should look something like:
*5
**2
***1
*9
**7

 

What do you think is the easier way to do it? Thanks!

 

You mean some think like this mate..

<?php

$array=array("123","123123","123123123","123","123123","123123123","123","123123","123123123");


$array[0]="level 1";


$array[3]="level 2";


$array[6]="level 3";


foreach($array as $key){

echo "<br>$key<br>";
}
?>

redarrow, do you ever bother trying your code before posting it?

 

<?php
$array = array(5 => "001", 2 => "001001", 1 => "001001001", 9 => "002", 7 => "002001");

foreach ($array as $key => $val) {
   $count = strlen($val) / 3;
   for ($x = 0; $x < $count; $x++) {
      echo "*";
   } // end for
   echo "$key<br/>";
} // end foreach
?>

 

That physically shows what you want, however if you were wanting to somehow separate the list, like when it goes from 001 to 002, you would have to throw in a condition on $val to add a new <br/> or <div> or whatever else you want to do to divide it.

Thanks! So in my case it would be:

 

$array = array(5 => "001", 2 => "001001", 1 => "001001001", 9 => "002", 7 => "002001");

foreach ($array as $key => $val) {
   $count = strlen($val) / 3;
   for ($x = 0; $x < $count; $x++) {
      echo "<ul class=\"advance level\">";
      if ($x == $count-1)
          echo "<li>";
   }
   echo "$key";
   for ($x = 0; $x < $count; $x++) {
     if (!$x)
        echo "</li>";
     echo "</ul>";
   } 
}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.