2

I need to extract data from a multidimensional array

       array(2) {
          ["label"]=>
          string(6) "label1"
          ["children"]=>
          array(3) {
            [1]=>
            array(1) {
              ["label"]=>
              string(6) "label2"
            }
            [2]=>
            array(1) {
              ["label"]=>
              string(6) "label3"
            }
           [3]=>
           array(2) {
             ["label"]=>
             string(6) "label4"
             ["children"]=>
             array(2) {
               [1]=>
               array(1) {
                 ["label"]=>
                 string(6) "label5"
               }
               [2]=>
               array(1) {
                 ["label"]=>
                 string(6) "label6"
               }
            }
          }
        }
      }

into a table with the following structure:

 <table border="1">
      <tr>
       <td colspan="4">label1</td>
      </tr>
      <tr>
       <td colspan="1">label2</td>
       <td colspan="1">label3</td>
       <td colspan="2">label4</td>
      </tr>
      <tr>
       <td></td>
       <td></td>
       <td colspan="1">label5</td>
       <td colspan="1">label6</td>
      </tr>
     </table>

The depth and structure of the array are dynamic, but the basic rule stays the same.

Any ideea on how I may accomplish this? Thank you!

Kisaragi
  • 2,198
  • 3
  • 16
  • 28
md0
  • 21
  • 1

1 Answers1

0

Convert the multidimensional array to a single and then loop through the single, creating the html string that you need, ie:

Convert the array: see Convert multidimensional array into single array

Loop through the single array in a php script and echo the string to your browser:

<?php
  function createHtml($singleArray){
    $html = '<table border="1">';
    foreach($singleArray as $label){
      $colspan = 1;
      //If then statement that sets $colspan based on label

      $html .= '<tr>';
      $html .= '<td colspan="'.$colspan.'">'.$label.'</td>';
      $html .= '</tr>';
    }
    $html .= '</table>';
    echo $html;
  }

?>
Community
  • 1
  • 1
Craig
  • 456
  • 5
  • 14
  • Unfortunately, your solution only outputs one label per row (
    label1
    Array
    ). I need to have an arbitrary number of labels (s) per row, each with a "colspan" equal to the number of children in the array.
    – md0 Sep 06 '16 at 01:44