gpt4 book ai didi

php - 只打印第一轮 div 的循环 php

转载 作者:行者123 更新时间:2023-11-29 04:38:56 25 4
gpt4 key购买 nike

你好,我想让这个结构成为一个循环。该结构是通过对数据库的查询形成的。如何执行循环我已经翻了好几圈都找不到解决办法。

结构如下:

示例数据库:

id | NombrePelicula | Director | ano | 


1 | Taxi Driver | Martin Scorsesse | 1976

2 | The color of money | Martin Scorsesse | 1986

3 | Spartacus | Stanley Kubrick| 1960

4 | After Hours | Martin Scorsesse | 1985

5 | My name is nobody | Sergio Leone | 1973

查询:

$lista="SELECT * FROM peliculas ORDER BY  id desc";

$listado=mysqli_query($Conex, $lista);



bucle:

while($x=mysqli_fetch_array($listado)){

$id=$x["id"];
$director=$x["director"];
$ano=$x["ano"];
$pelicula=$x["NombrePelicula"];



<div class="director"><span class="director-texto"><?php echo $director?></span></div></div>

echo $pelicula;


}

我希望它以这种方式出现

Martin Scorsse-----------

Taxi Driver

Raging Bull

The Color of Money

Stanley Kubrick------------

Spartacus

Dr. Strangelove

The Shining

Sergio Leone---------

Once Upon a Time in America

A Fistful of Dollars

我只会对数据库进行查询。无需为每个导演制作一个循环。

我的意思是,对于围绕导演的名字然后在他的电影下面的每个循环,只打印一次。我试过有条件地给出很多圈,但我设法找到了解决方案

最佳答案

您可以通过执行 ORDER BY director 来做到这一点在您的查询中,然后在循环时检查当前的 director和上次导演一样,只打印director更改时的名称 -

$lista="SELECT * FROM peliculas ORDER BY director";

$listado=mysqli_query($Conex, $lista);

$currentDirector = ""; // simple var to hold current director

while($x=mysqli_fetch_array($listado)){

$id=$x["id"];
$director=$x["director"];
$ano=$x["ano"];
$pelicula=$x["NombrePelicula"];

if($director ! = $currentDirector) { // if director not the same as the current director, echo header
{ ?>
<div class="director"><span class="director-texto"><?php echo $director?></span></div>
<?php
$currentDirector = $director; // set this director to current director
}

echo $pelicula."<br />";
}

如果你想把导演和电影包装在<div>中你会做这样的事情

$lista="SELECT * FROM peliculas ORDER BY director";

$listado=mysqli_query($Conex, $lista);

$currentDirector = ""; // simple var to hold current director

while($x=mysqli_fetch_array($listado)){

$id=$x["id"];
$director=$x["director"];
$ano=$x["ano"];
$pelicula=$x["NombrePelicula"];

if($director ! = $currentDirector) { // if director not the same as the current director, echo header
{
if($currentDirector != "") { // if not the 1st director, close the last director div before we open a new director div
echo "</div>"; // closes last div
}
?>
<div class="director"><span class="director-texto"><?php echo $director?></span><br />
<?php
$currentDirector = $director; // set this director to current director
}

echo $pelicula."<br />";
}
echo "</div>"; // close the last director div

关于php - 只打印第一轮 div 的循环 php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33930683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com