2010-11-19 85 views
0

如果我有一個檢索記錄的while循環,我希望能夠在循環進行時將記錄封裝在一定數量的記錄之後對記錄進行分隔。分隔記錄PHP

(使用while循環):

Record 1 
Record 2 
Record 3 
Record 4 
Record 5 
Record 6 
Record 7 

但我需要組的記錄是這樣的:

<div class="wrap"> 
Record 1 
Record 2 
Record 3 
</div> 
<div class="wrap"> 
Record 4 
Record 5 
Record 6 
</div> 
Record 7 

因此,當它超過3個以上就應該換,每3計數。

回答

4
$index = 0; 

while (...) { 
    if ($index == 0) { 
     echo '<div class="wrap">'; 
    } elseif (($index % 3) == 0) { 
     echo '</div><div class="wrap">'; 
    } 

    // Output your stuff 

    $index++; 
} 

if ($index != 0) { 
    echo '</div>'; 
} 
+0

好東西。謝謝 :) – MacMac 2010-11-19 18:32:46

1
<?php 

// Dummy data 
$records = array('1','2','3','4','5','6','7'); 

// While we have at least 3 records, group them 
while (count($records) > 3) { 
    $subs = array_splice($records,0,3); 
    print '<div class="wrap">'.implode(PHP_EOL, $subs).'</div>'; 
} 

// Dump the rest 
print implode(PHP_EOL, $records) 

?>