gpt4 book ai didi

PHP 分组和循环

转载 作者:行者123 更新时间:2023-11-29 20:37:27 24 4
gpt4 key购买 nike

我如何按技能对其进行分组并回显每项技能的所有照片。

SELECT skills.teacher, skills.student, skills.skill, profile.photo
FROM skills
INNER JOIN profile ON skills.student = profile.username
WHERE teacher = 'teach1'

teacher | student | skill | photo
------- | -------- | ------ | ------------
teach1 | student1 | skill1 | student1.jpg
teach1 | student2 | skill1 | student2.jpg
teach1 | student3 | skill2 | student3.jpg
teach1 | student3 | skill1 | student3.jpg
teach1 | student4 | skill3 | student4.jpg
teach1 | student1 | skill2 | student1.jpg

我强调这是一个例子。我实际上不知道“技能”的名称,因为它们是学生们创造的。不知道总共会列出多少技能。我不知道哪些用户会给哪些老师添加哪些技能。

我尝试过 while 循环和 foreach 循环。我只是不知道如何对其进行分组以及使用什么类型的循环...

我需要我的最终结果来让我 echo 。

<div>skill1 
<img src="student1.jpg">
<img src="student2.jpg">
<img src="student3.jpg">
...
...
...
</div>

<div>skill2
<img src="student1.jpg">
<img src="student3.jpg">
...
...
...
</div>

<div>skill3
<img src="student4.jpg">
...
...
...
</div>

最佳答案

首先,按技能排序,以便按顺序排列它们:

SELECT skills.teacher, skills.student, skills.skill, profile.photo
FROM skills
INNER JOIN profile ON skills.student = profile.username
WHERE teacher = 'teach1'
ORDER BY skills.skill

在 while 循环之外分配一个变量(在本例中为 $lastSkill)。检查它是否改变,并相应地输出内容。看看下面的例子。您的 PHP 代码看起来与此类似:

$lastSkill = null;

while ( $row = fetchrow() )
{
if ( $row['skill'] !== $lastSkill )
{
//Don't close a div, if it's the first row
if ( $lastSkill !== null )
echo '</div>';

//We've moved onto a new row, echo it out
echo '<div>' . $row['skill'];
//Store the lastSkill
$lastSkill = $row['skill'];
}

echo '<img src="' . $row['photo'] . '">';
}

关于PHP 分组和循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38734202/

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