连接表的foreach循环

时间:2015-04-18 12:56:08

标签: php mysql

我试图在循环中列出用户,但我想将city_name保留在循环之外。我需要另一个查询或if语句吗?

我最终想要的结果是什么:

伦敦用户: 詹姆斯,鲍勃

纽约用户: DAVID

users table
====================
id  user_name   user_city_id  user_type
1   Helen       2             NA
2   James       1             PREMIUM
3   David       1             NORMAL
4   Bob         1             NORMAL

cities table
=============
city_id  city_name  city_status
1        London     1
2        New York   1
3        Paris      0

<?php 

    $getcities = $db->get_rows("
        SELECT * 
        FROM users
        JOIN cities 
        ON cities.city_id = users.user_city_id
        WHERE city_status = '1'
        AND user_type IN ('NORMAL','PREMIUM')
    ");

?>

<h1><?php echo $row->city_name ?> USERS</h1>

<?php
    foreach($getcities as $row) {
?>

<h2><?php echo $row->user_name ?></h2>

<?php
    }
?>

2 个答案:

答案 0 :(得分:2)

如果您想按城市列出用户,您需要切换您的联接,或者您需要在应用程序级别重新构建数据,这对IMO来说永远不会好,但有时是必要的。

您的示例存在很多问题,但要按照您的目标执行操作,请将SQL更改为

SELECT * 
FROM cities
JOIN users
ON cities.city_id = users.user_city_id
WHERE city_status = '1'
AND user_type IN ('NORMAL','PREMIUM')

然后

<?php
$lastCity = null;
foreach($getcities as $row):
?>

    <?php if($row->city_name !== $lastCity): $lastCity = $row->city_name; ?>
        <h1><?php echo $row->city_name ?> USERS</h1>
    <?php endif; ?>

    <h2><?php echo $row->user_name ?></h2>

<?php
endforeach;
?>

答案 1 :(得分:2)

您可以使用SQL查询执行此操作。

    SELECT cities.city_name, GROUP_CONCAT(users.user_name) AS names
    FROM users INNER JOIN cities ON cities.city_id = users.user_city_id
    WHERE city_status = '1' AND user_type IN ('NORMAL','PREMIUM')
    GROUP BY cities.city_id

在你的PHP中

    foreach($getcities as $row) {
          echo $row->city_name . ": " . $row->names;
    }