dqndc26628 2013-05-14 22:56
浏览 80
已采纳

如何在模板端的一个foreach中将数组拆分为两个表行“<tr>”

Due to working with a restricted working environment, I need to put half of this array into one table row and another half into another .

This is the array (already sorted in order of what I need):

Array
(
    [product] => KFE-1221        
    [description] => Classic Blue                                        
    [current_stock] => 630
    [purchase_order] => 
    [total_sales] => 0
    [avail_to_sell] => 630
    [size_run1] => 15
    [size_run2] => 62
    [size_run3] => 122
    [size_run4] => 113
    [size_run5] => 102
    [size_run6] => 92
    [size_run7] => 63
    [size_run8] => 61
    [size_run9] => 0
    [size_run10] => 0
)

I need to split the array at "size_run1" - "size_run10" into a separate table row.

Previously, I had this to display the array into a table (standard foreach) when I didn't need the size_run. Due to request I am adding it in. (And yes I am using deprecated php)

<?php
while($data = mssql_fetch_assoc($result_ats)) {
    if ($data['avail_to_sell'] <= 0){   
    echo '<tr class="error">';
      }
    else {
    echo '<tr>';
      }
    foreach($data as $k => $v){

        echo '<td>'.$v.'</td>';
        echo '</tr>';

     }
  }
?>

The reason I want to keep it as one array is because I am using one query for all the information, and with the huge database that I'm working with, it makes more sense for me to split this up on template side rather than have separate arrays and add a process of matching the product to the size_run.

What is the best way of doing this without having the split the array up into different arrays?

My desired output, which is to split up array '$v' into two separate tables like below:

  <tr>
    <th>product</th>
    <th>description</th>
    <th>current_stock</th>
    <th>purchase_order</th>
    <th>total_sales</th>
    <th>avail_to_sell</th>
  </tr>
  <tr>
    <th>size_run1</th>
    <th>size_run2</th>
    <th>size_run3</th>
    <th>size_run4</th>
    <th>size_run5</th>
    <th>size_run6</th>
    <th>size_run7</th>
    <th>size_run8</th>
    <th>size_run9</th>
    <th>size_run10</th>
  </tr>
  • 写回答

2条回答 默认 最新

  • donglu3243 2013-05-14 23:19
    关注

    Something like this:

    $firstRow = array('product', 'description', 'current_stock', 'purchase_order', ... );
    $secondRow = array('size_run1', 'size_run2', 'size_run3', ... );
    
    while($data = mssql_fetch_assoc($result_ats)) {
    
      echo '<tr>';
    
      foreach($firstRow as $key){
    
        echo '<td>' . $data[$key] . '</td>';
    
      }
    
      echo '</tr>';  
      echo '<tr>';
    
      foreach($secondRow as $key){
    
        echo '<td>' . $data[$key] . '</td>';
    
      }
    
      echo '</tr>';    
    
    }
    

    Still maintainable if you want to change the keys.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?