PHP分组和LOOPS

时间:2016-08-03 04:04:17

标签: php mysql pdo

我如何通过技巧对其进行分组,并回应每种技能的所有照片。

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循环。我只是无法弄清楚如何对此进行分组以及使用何种类型的循环...

我需要我的最终结果让我回应。

<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>

2 个答案:

答案 0 :(得分:1)

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

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'] . '">';
}

答案 1 :(得分:-1)

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

**ORDER BY WHATEVER YOU WANT PUT IN PLACE OF ?.**