我希望生成如下所示的 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 表格。
我很难概念化将这一切放在一起的逻辑。
谢谢!
最佳答案
您走在正确的道路上。它会是这样的:
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>';
关于PHP嵌套foreach循环显示表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15480939/