使用php显示多个数据

lqfhib0f  于 2023-06-28  发布在  PHP
关注(0)|答案(1)|浏览(141)
<?php 
    $query = "SELECT count(floor_hall.o_id) as count, office_hall.*,floor_hall.* 
            FROM 
`floor_hall` 
            INNER JOIN office_hall on office_hall.o_id=floor_hall.o_id 

            group by floor_hall.o_id";
    $result = mysqli_query($conn, $query);
    
    $rows=array();
    while ($row = mysqli_fetch_assoc($result))
        $rows[] = $row;
    
    // Fetch and display the results
    foreach ($rows as $row) {
        $id = $row['office_name'];
        $count = $row['count'];
        $fname = $row['f_name'];
        
        echo "Area: $id, Count: $count, <br>$fname <br>";
    }
    
    ?>

我试着用这个,它只显示这个

我如何获得这些数据

Area: Nex Tower, Count: 1,
20th floor

Area: Nex54, Count: 3,
10th floor
11th floor
12th floor

floor_hall

office_hall

这是我的数据库的样本

6jjcrrmo

6jjcrrmo1#

您可以使用GROUP_CONCAT()将所有结果的值组合到一个组中。然后在PHP中使用explode()将它们分开,这样就可以在不同的行中显示它们。
由于您没有发布表模式,我在下面做一些假设。

$query = 'SELECT o.office_name, COUNT(*) AS count, 
                GROUP_CONCAT(f.f_name ORDER BY f.f_id) AS names, 
                GROUP_CONCAt(f.f_id ORDER BY f.f_id) AS floor_ids
          FROM floor_hall AS f
          JOIN office_hall AS o ON f.o_id = o.o_id
          GROUP BY f.o_id';
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($result)) {
    $id = $row['office_name'];
    $count = $row['count'];
    echo "Area: $id, Count: $count, <br>";
    $floors = explode(',', $row['names');
    $floor_ids = explode(',', $row['floor_ids']);
    foreach ($floors AS $i=> $fname) {
        echo "{$floor_ids[$i]}: $fname<br>";
    }
}

相关问题