简体   繁体   中英

Don't repeat values in loop

I've the following query

询问

As you see jigsaw repeats twice because the movie has two categories but i would like to echo both categories but not twice the movie..

<?php
    while ($mInfo = $testquery->fetch(PDO::FETCH_ASSOC)) {
?>

    <div class="col-xs-6 col-sm-4 col-md-3">

    <a href="movie.php?title=<?php echo $mInfo['titleEN']; ?>&m=<?php echo $mInfo['imdbID']; ?>" title="<?php echo $mInfo['titleEN']; ?>" alt="<?php echo $mInfo['titleEN']; ?>" target="_self">
    <div class="movie-info">

        <img src="assets/images/poster/<?php echo $mInfo['poster']; ?>.jpg" alt="<?php echo $mInfo['titleEN']; ?>">
    </div>



    <div class="movieinformation">
        <div class="movie-title"><?php echo $mInfo['titleEN']; ?></div>
            <div class="movie-categories">I WOULD LIKE TO ECHO THE CATEGORIES HERE</div>
            </div>


            </a>

        </div>
    <?php
    }
    ?>

So far i just could do it, could anyone help me with that?

Here's a concept for such tasks. I kept it with general names and left out html on purpose.

$oldMainId = null; // Initialize to null to start with. This will be needed later.
while ($item = $result->fetch()) { // get your items (movies in your case)
    if($oldMain != $item['mainId']) {
        // only show title if you haven't yet
        echo $item['mainTitle'];
    }
    // always show the category though
    echo $item['sub'];

    // re-set the 'old' variable. 
    $oldMainId = $item['mainId'];
}

I would use

OPTION 1

 $res = $stmt->fetchAll(PDO::FETCH_GROUP);

Then it will group on the first column, assuming that is movie ID, or something unique to the movie you would get multiple rows in a nested array for that movie.

Then when you iterate thorough them you can loop over the nested array for the genre stuff

OPTION 2

Another option is to use GROUP_CONCAT and group by the movie id,

 SELECT GROUP_CONCAT(genre) AS genre, ... WHERE ... GROUP BY movieID

But be aware that GROUP_CONCAT does have a setting for max length and it will silently truncate your data if it exceeds it.

OPTION 3

You can build the structure yourself (same as fetch group does)

 $data = [];
 while ($mInfo = $testquery->fetch(PDO::FETCH_ASSOC)) {
      $key = $mInfo['movieid']
      if(!isset($data[$key]))  $data[$key] = [];

     $data[$key][] = $mInfo;

 }

Then go through that and do your html by using a second foreach($data as ...) It has to be done after organizing the data as the order of the result is unknown.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM