仅显示状态标头一次,并仍显示该状态下的所有地址

时间:2019-02-21 03:14:02

标签: php mysqli

我正在寻找一种显示方式:

<h1>State1</h1>

<h2>City1</h2>
<p>Address1</p>


***if next address is in the same state:*

<h2>City2</h2>
<p>Address2</p>

<hr>

**if next address is NOT in the same state

<h1>State2</h1>

<h2>City3</h2>
<p>Address3</p>

我正在使用:

<?php    
    $query = "SELECT * FROM places";
    $select_all_places = mysqli_query($connection, $query);

    while($row = mysqli_fetch_assoc()){
    $p_state = $row['p_state'];
    $p_city = $row['p_city'];
    $p_address = $row['p_address'];

    ?>

    <h1><?php echo $p_state ?></h1>
    <h2><?php echo $p_city ?></h2>
    <p><?php echo $p_address ?></p>

    <?php } ?>

1 个答案:

答案 0 :(得分:1)

在这里查看代码。我在您的echo语句上添加了一些分号,并将查询变量添加到了mysqli_fetch_assoc方法中。我还添加了一些评论,以帮助您了解我在这里所做的事情。

<?php
$query = "SELECT * FROM places";
$select_all_places = mysqli_query($connection, $query);

// This will be the state we are currently on. Start it as null.
$current_state = '';

while($row = mysqli_fetch_assoc($select_all_places)){
    $p_state = $row['p_state'];
    $p_city = $row['p_city'];
    $p_address = $row['p_address'];

?>
    <!-- Check if variable state is equal to current row's state. -->
    <?php if($current_state != $p_state): ?>

        <!-- Echo state if they aren't equal  -->
        <h1><?php echo $p_state; ?></h1>

        <!-- Assign new current state -->
        <?php $current_state = $p_state; ?>
    <?php endif; ?>
    <h2><?php echo $p_city; ?></h2>
    <p><?php echo $p_address; ?></p>

<?php } ?>