2014-02-21 45 views
0

我不知道如何循環訪問該數組並將其顯示到HTML表格中。子數據是動態的,可以是無限的。任何人都可以給我一個線索?謝謝!循環遍歷無限的兒童數組並顯示到表

(
    [0] => Array 
     (
      [Discount] => Array 
       (
        [id] => 8 
        [parent_id] => 0 
        [lft] => 1 
        [rght] => 6 
        [name] => Discount 1 
        [value] => 25 
       ) 

      [children] => Array 
       (
        [0] => Array 
         (
          [Discount] => Array 
           (
            [id] => 10 
            [parent_id] => 8 
            [lft] => 2 
            [rght] => 5 
            [name] => Child of D1 
            [value] => 32 
           ) 

          [children] => Array 
           (
            [0] => Array 
             (
              [Discount] => Array 
               (
                [id] => 11 
                [parent_id] => 10 
                [lft] => 3 
                [rght] => 4 
                [name] => The 1.1.1 
                [value] => 65 
               ) 

              [children] => Array 
               (
               ) 

             ) 

           ) 

         ) 

       ) 

     ) 

) 

我知道我不能只是做:

foreach($discounts as $discount){ 
    echo "<div>{$discount['Discount']['name']}</div>"; 
} 
+0

[嵌套到無限的深度多維數組(HTTP的可能重複。 COM /問題/ 4312425 /多維陣列嵌套到無限深度) –

回答

0

試試這個

foreach ($Discount as $children => $value) { 
    echo "<div>{$discount['Discount']['$children']['name']}</div>"; 
} 
0

您需要遞歸正常地生成HTML。這是一個我希望有幫助的例子。這不正是你怎麼會想生成最終的HTML,但這應該讓你開始在正確的軌道上://計算器:

$data = array(
    0 => array(
     'discount' => array(
      'id' => 8, 
      'parent_id' => 0, 
      'lft' => 1, 
      'rght' => 6, 
      'name' => 'Discount 1', 
      'value' => 25, 
     ), 
     'children' => array(
      0 => array(
       'discount' => array(
        'id' => 10, 
        'parent_id' => 8, 
        'lft' => 2, 
        'rght' => 5, 
        'name' => 'Child of D1', 
        'value' => 32, 
       ), 
       'children' => array(
        0 => array(
         'discount' => array(
          'id' => 11, 
          'parent_id' => 10, 
          'lft' => 3, 
          'rght' => 4, 
          'name' => 'The 1.1.1', 
          'value' => 65, 
         ), 
         'children' => array(), 
        ) 
       ) 
      ) 
     ) 
    ) 
); 

$html = getHtml($data); 

/** 
* This function is called recursively to generate the necessary HTML 
* @param array $data 
*/ 
function getHtml(array $data) 
{ 
    // This is your base conditon to end the recursion. It stops once it hits an empty children array 
    if (empty($data)) { 
     return; 
    } 
    $data = $data[0]; // will have to tweak this if you have more than 1 element per array 
    $html = sprintf('<div id="%d" name="%s">', $data['discount']['id'], $data['discount']['name']); 
    $html .= getHtml($data['children']); // this recursive call generates inner HTML 
    $html .= '</div>'; 
    return $html; 
} 

// See the result 
var_dump($html);