从数组中获取每个变量

时间:2012-02-12 18:21:57

标签: php mysql

我正在尝试检索与社会相关的标签。下面的代码有效,但它只检索第一个标记而不是表中的其余标记。

$user = $_SESSION['user'];
$society = $_SESSION['society'];

$soc_q = mysql_query("SELECT socID, creator, socName, type, datetime
     FROM societies.society WHERE socName = '$society'");
$soc_row = mysql_fetch_array($soc_q, MYSQL_ASSOC);


$tag_q = mysql_query("SELECT society.socID, tagID, name
     FROM societies.society
     INNER JOIN societies.tags ON society.socID = tags.socID
     WHERE society.socID = '$soc_row[socID]'");
$tag_row = mysql_fetch_array($tag_q, MYSQL_ASSOC);

$the_tags = $tag_row['name'];

if (!@$_SESSION['existing_tags']) {
    $_SESSION['existing_tags'] = $the_tags;
}

$existing_tags = $_SESSION['existing_tags'];
$tags = explode(' ', $the_tags);

// ajax
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && @$_GET['tag']) {
    $match = array();
    foreach ($tags as $tag) {
        if (stripos($tag, $_GET['tag']) === 0) {
            $match[] = $tag;
        }
    }

    echo json_encode($match);

    exit;

1 个答案:

答案 0 :(得分:2)

你必须像这样在循环中加载标记(获取每一行):

$the_tags = array();
while( $tag_row = mysql_fetch_assoc( $tag_q)){
    $the_tags[] = $tag_row['name'];
}

编辑:使用GROUP BY

如果您愿意使用mySQL和元素分组,可以使用GROUP_CONCAT(如果您只需要标记名称):

$tag_q = mysql_query("
     SELECT GROUP_CONCAT( DISTINCT tags.name SEPARATOR ', ') as `tags`
     FROM societies.society
     INNER JOIN societies.tags ON society.socID = tags.socID
     WHERE society.socID = '$soc_row[socID]'
     GROUP BY NULL");
$tag_row = mysql_fetch_array($tag_q, MYSQL_ASSOC);
$tag_names = explode( ', ', $tag_row['tags']);

上面的代码没那么有用,但是当你将它与第一个查询结合起来时,你会得到:

$soc_q = mysql_query("SELECT socID, creator, socName, type, datetime,
     GROUP_CONCAT( DISTINCT tags.name SEPARATOR ', ') as `tags`
     FROM society
     LEFT JOIN societies On societies.socID = society.socID
     LEFT JOIN tags ON societies.tagsID = tags.socID
     WHERE socName = '$society'
     GROUP_BY society.id");
$soc_row = mysql_fetch_array($soc_q, MYSQL_ASSOC);

注意:使用数据库名称为表添加前缀会使您的代码难以阅读,因为一旦您这样做,其他时间就不会。