我有一个输出以下数据的查询:
Treatment ID --------- Treatment_Name ---------- Customer_type
1 Treatment 1 Ladies
1 Treatment 1 Mens
3 Treatment 2 Ladies
4 Treatment 3 Mens
我需要遍历这个并输出一个类似的结构:
<div class="mens ladies"> <!-- these are read from the customer_type column -->
<h4>Treatment 1</h4> <!-- this is read from the treatment_name column -->
</div>
所以基本上按治疗名称(或ID)进行分组,然后输出与此治疗相关的所有客户。
来自ColdFusion背景我认为使用查询查询等会很容易。但是我一直在努力想出一个PHP解决方案。
我试图做一个while循环,只显示数据,如果treatment_name已经改变,这似乎工作正常,但我不知道如何显示与此相关的customer_types。
有什么想法吗?感谢。
修改 以下是使用mysqli_fetch_all从数据库返回的查询的副本:
array (size=22)
0 =>
array (size=3)
0 => string 'Mens' (length=4)
1 => string '1' (length=1)
2 => string 'treatment 1' (length=11)
1 =>
array (size=3)
0 => string 'Ladies' (length=6)
1 => string '1' (length=1)
2 => string 'treatment 1' (length=11)
2 =>
array (size=3)
0 => string 'Kids' (length=4)
1 => string '2' (length=1)
2 => string 'treatment 2' (length=11)
3 =>
array (size=3)
0 => string 'Ladies' (length=6)
1 => string '2' (length=1)
2 => string 'treatment 2' (length=11)
4 =>
array (size=3)
0 => string 'Mens' (length=4)
1 => string '2' (length=1)
2 => string 'treatment 2' (length=11)
5 =>
array (size=3)
0 => string 'Mens' (length=4)
1 => string '3' (length=1)
2 => string 'treatment 3' (length=11)
6 =>
array (size=3)
0 => string 'Kids' (length=4)
1 => string '3' (length=1)
2 => string 'treatment 3' (length=11)
7 =>
array (size=3)
0 => string 'Ladies' (length=6)
1 => string '3' (length=1)
2 => string 'treatment 3' (length=11)
8 =>
array (size=3)
0 => string 'Ladies' (length=6)
1 => string '4' (length=1)
2 => string 'treatment 4' (length=11)
它以相同的格式继续......
答案 0 :(得分:1)
希望这能回答你的问题:
<?php
$link = mysqli_connect("hostname","username","password","database","port") or die("Error " . mysqli_error($link));
$query = "SELECT treatment_name,Customer_type from Treatments" or die("Error at.." . mysqli_error($link));
$result = $link->query($query);
while($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
//I have used this sample array: Try and make your result set this way
$data = array(
array('treatment_name'=>'Treatment1','Customer_type'=>'Mens'),
array('treatment_name'=>'Treatment1','Customer_type'=>'Ladies'),
array('treatment_name'=>'Treatment2','Customer_type'=>'Mens')
);
foreach ($data as $key => &$value) {
$temp[$value['treatment_name']][$key] = $value['Customer_type'];
}
//echo "<pre>";
//print_r($data);
//print_r($temp);
//die;
foreach($temp as $key => $value){
echo "<div class = \"";
foreach($value as $key2 => $value2)
echo " ". $value2. " ";
echo "\"><h4>".$key."</h4></div></br>";
}
?>
//Output
<div class = " Mens Ladies "><h4>Treatment1</h4></div></br><div class = " Mens "><h4>Treatment2</h4></div></br>
您可以使用注释行检查数据并进行相应调整。 顺便说一句,这段代码直接将输出打印为html,因此您的浏览器将呈现它。如果您想要内容,请右键单击页面并查看源代码!