3 回答

TA貢獻1793條經驗 獲得超6個贊
如果我理解你的問題,我想你應該試試這個:
<div id="category_case_holder">
<table>
<tr>
<?php
$sql = "SELECT * FROM users WHERE status = 'active' AND usertype = 'advertiser'";
$result = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
$resultNumber = count($result);
for ($i = 1; $i <= $resultNumber; $i++) {
echo "<td>";
$key = $i - 1;
if (isset($result[$key])) {
$filename = "data/profile/$i/main/profile.jpg";
if (file_exists($filename)) {
echo '<div id="prime"><a href="profile.php?id='.htmlspecialchars($result[$key]['user_id']).'"><img src="data/profile/'.htmlspecialchars($result[$key]['user_id']).'/main/profile.jpg" alt="Profile" height="100%" width="100%"></a></div>';
} else {
echo '<div id="prime"><a href="profile.php?id='.htmlspecialchars($result[$key]['user_id']).'"><img src="data/profile/0/main/profile.jpg" alt="Profile" height="100%" width="100%"></a></div>';
}
} else {
echo '<div id="prime"><img src="data/profile/0/main/advert.jpg" alt="Profile" height="100%" width="100%"></div>';
}
echo "</td>";
if (($i % 6) == 0 && $i <= $resultNumber) {
echo "</tr>";
echo "<tr>";
}
}
?>
</tr>
</div>

TA貢獻1796條經驗 獲得超7個贊
以下是完全未經測試的,可能還沒有看到數據,也沒有關于個人資料圖像的答案,但總體目標是將結果數組分解成小塊——這是理想的選擇array_chunk。
<div id="category_case_holder">
<?php
$sql = "SELECT * FROM `users` WHERE `status` = 'active' AND `usertype` = 'advertiser'";
$result = $conn->query( $sql )->fetch_all( MYSQLI_ASSOC );
# a placeholder in the path will be substituted later using sprintf or printf
$filepath = 'data/profile/%s/main/profile.jpg';
if( !empty( $result ) ){
# split the recordset array into chunks - 6 records long.
# Each chunk will be a row from recordset.
$chunks=array_chunk( $result, 6 );
foreach( $chunks as $chunk ){
echo '<div>';
foreach( $chunk as $i => $rs ){
$filename=file_exists( sprintf( $filepath, $i ) ) ? sprintf( $filepath, $rs['user_id'] ) : sprintf( $filepath, '0' );
# ID attributes MUST be unique.
# substitue placeholders for values from this row data
printf('
<div class="prime">
<a href="profile.php?id=%s">
<img src="%s" alt="Profile" height="100%" width="100%">
</a>
</div>',
htmlspecialchars( $rs['user_id'] ),
$filename
);
}
echo '</div>';
}
}else{
echo '<div id="prime"><img src="data/profile/0/main/advert.jpg" alt="Profile" height="100%" width="100%"></div>';
}
?>
</div>

TA貢獻1797條經驗 獲得超4個贊
您可以使用該array_chunk()方法輕松實現。
例子:
//set it to whatever limit you want.
$limit = 6;?
// this will divide the array into x number of chunks based on y limit.
$chunks = array_chunk($result, limit);
foreach($chunks as $chunk){
? ?echo '<div>';
? ?foreach($chunk as $chunkItem){
? ? ? // your stuff here
? ?}
? ?echo '</div>';
}?
- 3 回答
- 0 關注
- 181 瀏覽
添加回答
舉報