抱歉,英语不好,标题也不好!
我有“职位”这个桌子
id title
1 test Thread
2 hello
3 just
“标签”也是如此
tagid tagname
1 test
2 russia
3 new site
所以有一个post_tags
tagid postid
1 1
2 1
3 1
下面我需要一个来自var_dump的数组:
$posts = array(
1 => array(
'title' => 'test Thread',
'tags' => array(
'test', 'russia', 'new site',
),
),
2 => array(
'title' => 'hello',
'tags' => NULL
),
3 => array(
'title' => 'just',
'tags' => NULL
),
)
我试着去做,但我没有得到我想要的。
SELECT `post`.`id`, `post`.`title`, `tags`.`tagname` FROM `post`
LEFT JOIN `post_tags` ON `post_tags`.`tagid` = `post`.`id`
LEFT JOIN `tags` ON `post_tags`.`tagid` = `tags`.`tagid`
接下来我将进入SQL:
id title tagname
1 test Thread test
1 test Thread russia
1 test Thread newsite
2 hello NULL
3 just NULL
$query = mysql_query("SELECT `post`.`id`, `post`.`title`, `tags`.`tagname` FROM `post`
LEFT JOIN `post_tags` ON `post_tags`.`tagid` = `post`.`id`
LEFT JOIN `tags` ON `post_tags`.`tagid` = `tags`.`tagid`");
$posts = array();
while ($row = mysql_fetch_assoc($query))
{
$posts[] = $row;
}
var_dump($posts);
谢谢!
发布于 2012-04-10 21:40:03
查询很好。您只需要循环中的一些逻辑:
while ($row = mysql_fetch_assoc($query))
{
if (isset($posts[$row['id']])) {
$posts[$row['id']]['tags'][] = $row['tagname'];
}
else {
$posts[$row['id']] = array(
'title' => $row['title'],
'tags' => $row['tagname'] === null ? null : array($row['tagname'])
);
}
}
如果您已经看到一个具有相同post id的行,那么从当前行中您所需要的只是标记名(因此请将其添加到“标记”数组中)。如果这是第一次看到带有此post id的行,只需将其添加到$posts
中,则要谨慎地将“标记”设置为null
或带有一个元素的数组。
发布于 2012-04-10 21:43:26
您不能从mysql数据库中获得多维数组。如果您想要的话,您必须对结果进行自己的后处理。可能是这样吧?
$posts = array();
while ($row = mysql_fetch_assoc($query))
{
if (!isset($posts[$row['id']])) {
$posts[$row['id']] = array();
$posts[$row['id']]['title'] = $row['title'];
$posts[$row['id']]['tags'] = array();
}
if ($row['tagname'] != null) $posts[$row['id']]['tags'][] = $row['tagname'];
}
发布于 2012-04-10 21:41:03
试试这个:
while ($row = mysql_fetch_assoc($query))
{
if( !isset( $posts[$row["id"]] ) ) {
$posts[ $row["id"] ] = array( "title" => $row["title"], "tags" => array() );
}
array_push( $posts[ $row["id"] ][ "tags" ], $row["tagname"] );
}
我不能调试它,所以告诉我如果你有任何错误
https://stackoverflow.com/questions/10096764
复制相似问题