PHP array custom looping -


i want create custom toc(table of contents) generated array. example array values looks :

$angka = array(1,11,12,13,2,21,22,23); 

when values containts more 1 digit (11,12,13,21,22,23, etc) should categorized "sub". otherwise, should categorized "non-sub". desired output should https://jsfiddle.net/thekucays/azordcv5/2/

in order achieve that, loop array, check current index, previous index, , next index length. code looks this

<?php $angka = array(1,11,12,13,2,21,22,23); $hitung = count($angka);     $keys = array_keys($angka);  echo "<ul>"; foreach(array_keys($keys) $k){     if(strlen($angka[$keys[$k]])==1){         echo "<li>ini bukan sub</li>";       }     else if(strlen($angka[$keys[$k]])>1 && strlen($angka[$keys[$k-1]])==1){ //buka sub baru         echo "<li><ul>";         echo "<li>ini buka sub</li>";     }     else if(strlen($angka[$keys[$k]])>1 && strlen($angka[$keys[$k-1]])>1 && strlen($angka[$keys[$k+1]])>1){  //ini masih di dalem sub         echo "<li>ini sub tengah</li>";     }     else if(strlen($angka[$keys[$k]])>1 && strlen($angka[$keys[$k-1]])>1 && ($k<=$hitung || strlen($angka[$keys[$k+1]])==1)){  //akhir sub, tutup         echo "<li>ini sub akhir</li>";         echo "</ul></li>";     } } echo "</ul>"; 

?>

the problem is, in example code, foreach loop continue loop until array length +1 (which 8), , show "undefined offset" notice. how prevent that?

hi assuming array have same pattern (after main sub, there next 3 subs) can simplify code this

 <?php     $angka = array(1,11,12,13,2,21,22,23);      echo "<ul>";     $counter = 0;     foreach($angka $value){         $quotient = $value / 10;          if ($quotient == 0) { // meaning not - sub             echo "<li>ini bukan sub</li>";               $counter = 0; // reset sub - index         }         else { // display subs             switch ($counter) { //select sub type displayed                 case 0: // first sub                     echo "<li><ul>";                     echo "<li>ini buka sub</li>";                        break;                 case 1: //second sub                     echo "<li>ini sub tengah</li>";                 case 2: //third sub                     echo "<li>ini sub akhir</li>";                     echo "</ul></li>";             }             $counter++;         }     } echo "</ul>"; 

in case, can rid of indexing issues encountered now.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -