我找了大约一个小时。我甚至可能在寻找错误的东西,因为我确信这是一种常见的做法。在过去,我本来只是运行多个查询或者有硬编码的东西,但我正在尝试以最有效的方式做事。
我有一个带回这些数据的查询:
factoryId | serviceID | serviceName 1 1001 repair 1 1002 recycle 1 1003 transfer 2 1001 repair 2 1002 recycle 2 1003 transfer 3 1001 repair 3 1002 recycle 3 1003 transfer
我需要将其放入带标题的部分...... // switch语句从id确定工厂名称?> 工厂一
工厂二
工厂三
我认为解决方案是使用多维数组,但不确定如何编写数组,然后(2 foreach循环?)来回显格式化结果。
答案 0 :(得分:1)
这是你可以做的,我没有使用查询但是生成了一个类似于mysql_fetch_assoc()的数组;
<?php
$array[] = array("factory"=>"Factory One","serviceName"=>"repair");
$array[] = array("factory"=>"Factory One","serviceName"=>"recycle");
$array[] = array("factory"=>"Factory One","serviceName"=>"transfer");
$array[] = array("factory"=>"Factory Two","serviceName"=>"repair");
$array[] = array("factory"=>"Factory Two","serviceName"=>"recycle");
$array[] = array("factory"=>"Factory Two","serviceName"=>"transfer");
$array[] = array("factory"=>"Factory three","serviceName"=>"repair");
$array[] = array("factory"=>"Factory three","serviceName"=>"recycle");
$array[] = array("factory"=>"Factory three","serviceName"=>"transfer");
$group_array = array();
foreach($array as $key=>$val){
$group_array[$val["factory"]][] = $val["serviceName"];
}
foreach($group_array as $key=>$val){
echo '<b>'.$key.'</b><br />';
foreach($val as $k=>$v){
echo '-'.$v.'<br />';
}
}
?>
第一个循环类似于循环查询结果并创建一个组数组,然后最终循环组数组以显示数据。
答案 1 :(得分:0)
尝试以下代码。确保将查询附加ASC或DESC写入 factoryID
<?php
//Place a counter for factoryId
$countid_fid = 1;
$reset = 0; //this decides if the title should be printed or not. 1 means dont print.
//loop
while($row = mysql_fetch_object($q)) {
$fid = $row->factoryID;
if($countid_fid == $fid) {
if($reset = 0) {
echo $row->serviceName; //title
$reset = 1;
}
}else{
$reset = 0;
}
//rest of your code to show data
}
?>
答案 2 :(得分:0)
希望这个帮助
SELECT * FROM factory GROUP BY factoryId;