我希望生成如下所示的HTML表格。
|nick_name| bookmarked_sites |
-------------------------------
| admin | http://test1.com |
| | http://test2.com |
| | http://test3.com |
-------------------------------
| John | http://mysite.com |
-------------------------------
我使用$ wpdb查询数据库,并构建了一系列信息,如下所示:
$userquery = $wpdb->get_results("SELECT * FROM bookmarks");
print_r($userquery);
Array (
[0] => stdClass Object (
[id] => 1 [user_id] => 1 [post_id] => 1654,1532,1672,1610,1676 )
[1] => stdClass Object (
[id] => 3 [user_id] => 6 [post_id] => 1680,1654 ) )
我开始构建我的第一个foreach
来提取user_id
,然后我有一个嵌套的foreach
来为该用户提取post_id
。但我现在意识到,我不能轻易地根据这个概念构建HTML表格。
我很难概念化这一切的逻辑。
谢谢!
答案 0 :(得分:1)
你走在正确的轨道上。它会像:
echo '<table>';
foreach ($userquery as $user) {
//load sites into $loadedsites
$rowheight = count($loadedsites);
$c = 0;
//if there is a user without any sites, the rowheight would be 0.
//You need to deceide what to do than, because now it wouldnt show the user at all.
foreach($loadedsites as $site) {
if ($c==0)
echo '<tr><td rowspan="'.$rowheight.'">'.$user->user_id.'</td><td>'.$site->url.'</td></tr>';
else
echo '<tr><td>'.$site->url.'</td></tr>';
$c++;
}
}
echo '</table>';
答案 1 :(得分:1)
这是制作你的桌子的可能方法.. 使用查询中的数据..
<table>
<thead>
<tr>
<th>user_id<th>
<th>post_id<th>
</tr>
</thead>
<tbody>
<?php foreach($userquery as $uq): ?>
<tr>
<td><?php echo $uq['user_id']; ?></td>
<td>
<?php
$posts = explode(',', $uq['post_id']);
if(count($posts)>0):
?>
<table>
<?php foreach($posts as $p): ?>
<tr><td><?php echo $p; ?> </td></tr>
<?php endforeach; ?>
</table>
<?php else: ?>
No posts...
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>