2012-11-08 62 views
0

我剛剛問了一個關於關聯數組的問題,並使用foreach來檢索數據,但我正在努力想辦法從這個數據結構中構建我想要的表。PHP - 爲此數組結構構建表的最有效方法

我具有形式

Array 
(
    [204] => Array 
    (
     [1] => Array 
      (
       [leads] => 9 
      ) 

     [2] => Array 
      (
       [leads] => 15 
      ) 

    ) 

    [200] => Array 
    (
     [1] => Array 
      (
       [leads] => 7 
      ) 

     [2] => Array 
      (
       [leads] => 16 
      ) 

     [3] => Array 
      (
       [leads] => 5 
      ) 
) 

的陣列$dailytotals所以,我可以具有與任何數量的範圍內的子陣列的主陣列中的任何數目的子陣列。

到目前爲止,我已經成功建立我的表頭的宏偉任務:

<table> 
    <tr> 
     <th>Clinic</th> 

     <?php 
     // get unique columns - not all clinics will have leads for all columns 
     $columns = array(); 
     foreach ($dailytotals as $key => $arr) { 
      $columns = array_unique(array_merge($columns, array_keys($arr))); 
     } 

     foreach ($columns as $index => $campaignid) { 
      echo '<th>' . $campaignid . '</th>'; 
     } 
     ?> 
    </tr> 

但我現在完全陷入瞭如何構建表身。

我想建立的結構是:

Clinic | 1 | 2 | 3 | 
___________________________ 
204  | 9 | 15 | 0 | 
200  | 7 | 16 | 5 | 

回答

1

你需要一些嵌套循環。試試這個:

<table> 
    <tr> 
     <th>Clinic</th> 

     <?php 
     // get unique columns - not all clinics will have leads for all columns 
     $columns = array(); 
     foreach ($dailytotals as $key => $arr) { 
      $columns = array_unique(array_merge($columns, array_keys($arr))); 
     } 

     foreach ($columns as $index => $campaignid) { 
      echo '<th>' . $campaignid . '</th>'; 
     } 
     ?> 
    </tr> 
    <?php 
     foreach($dailytotals as $clinic => $data) 
     { 
      echo '<tr>'; 
      echo '<td>'.$clinic.'</td>'; 
      foreach($columns as $column) 
      { 
       echo '<td>'; 
       echo isset($data[$column]) ? $data[$column]['leads'] : 0; 
       echo '</td>'; 
      } 
      echo '</tr>'; 
     } 

    ?> 
</table> 
1

這段代碼沒有進行測試,但很少嘗試的修改(如果需要)

<table> 
    <tr> 
    <th>Clinic</th> 
    <?php 
    // get unique columns - not all clinics will have leads for all columns 
    $columns = array(); 
    $max=0; 
    foreach ($dailytotals as $key => $arr) { 
     $columns = array_unique(array_merge($columns, array_keys($arr))); 
    } 

    foreach ($columns as $index => $campaignid) { 
     echo '<th>' . $campaignid . '</th>'; 
     $max=$campaignid; 
    } 
    ?> 
    </tr> 

    <?php 
    $columns = array(); 
    foreach ($dailytotals as $key => $arr) { 
     for($i=0;$i< $max;$++) 
     { 
      echo "<tr>"; 
      if(is_set($arr[i]) 
      { 
       echo "<td>".$arr[i]."</td>"; 
      } 
      else 
      { 
       echo "<td>0</td>"; 
      } 
      echo "</tr>"; 
     } 
    } 
    ?> 
1

試試這個

foreach ($dailytotals as $key => $arr) { 
    echo '<tr>'; 
    foreach ($columns as $campaignid) { 
    $val = isset($arr[$campaignid]) ? $arr[$campaignid]['leads'] : 0; 
    echo '<td>' . $val . '</td>'; 
    } 
    echo '</tr>'; 
} 
相關問題