我有这个多维,我从列表中得到它。我希望该列表中的项目按"类别"分组,这是php代码:
foreach ($re_services as $re_serv){
$ows_Category = $re_serv->getAttribute("ows_OfferingCatType");
$ows_ServiceID = $re_serv->getAttribute("ows_Title");
$ows_Service = $re_serv->getAttribute("ows_OfferingsName_Edit");
$ows_Hours = $re_serv->getAttribute("ows_Hours");
$Service_Array []= array(
"Category" => $ows_Category,
"ServiceID" => $ows_ServiceID,
"Service" => $ows_Service,
"Hours" => $ows_Hours
); }
我的输出是:
大堆([0]=>数组([类别]=>造型[ServiceID:>Blow Dry-Male_104【服务】=>外螺纹吹干[小时]=>1.000000000000)[1] =>阵列([类别]=>造型[ServiceID]=>女士切块吹风机_101〔服务〕=>女士切割和吹干[小时]=>1.000000000000)[2] =>阵列([类别]=>造型[ServiceID]=>吹风时间更长_103【服务】=>更长的吹风时间[小时]=>2.000000000000000)[3] =>阵列([类别]=>造型[ServiceID]=>男士剪吹烘干_102〔服务〕=>男士切割和吹干[小时]=>1.000000000000)[4] =>阵列(【类别】=>超级服务[ServiceID]=>Half-Head_106【服务】=>半头[小时]=>1.000000000000)[5] =>阵列(【类别】=>超级服务[ServiceID]=>高亮显示/低亮度_105[服务]=>高亮/近光灯[小时]=>3.00000000000000)[6] =>阵列(【类别】=>超级服务[ServiceID]=>奢华护发素_109【服务】=>奢华美发[小时]=>4.00000000000000)[7] =>阵列([类别]=>技术[ServiceID]=>新娘发_108【服务】=>新娘头发[小时]=>4.00000000000000)[8] =>阵列([类别]=>技术[ServiceID]=>Hair Up_107[服务]=>Hair Up[小时]=>1.000000000000))
正如你所看到的,我有三个类别(风格,超级服务,技术)。现在我需要的输出是html标签,其值如下:
<select>
<optgroup label="Category">
<option value="ServiceID">Service Hours</option>
</optgroup> </select>
但没有任何与类别标签重复。我怎样才能做到这一点?
试试这个:
$categories = array();
foreach ($re_services as $re_serv){
$ows_Category = $re_serv->getAttribute("ows_OfferingCatType");
$ows_ServiceID = $re_serv->getAttribute("ows_Title");
$ows_Service = $re_serv->getAttribute("ows_OfferingsName_Edit");
$ows_Hours = $re_serv->getAttribute("ows_Hours");
$Service_Array []= array(
"Category" => $ows_Category,
"ServiceID" => $ows_ServiceID,
"Service" => $ows_Service,
"Hours" => $ows_Hours
);
//add the following part:
if(!in_array($ows_Category, $categories))
$categories[] = $ows_Category;
}
现在,您可以在$categories
上使用foreach
循环来打印正确的html标签:
echo '<select>';
foreach($categories as $category){
echo '<optgroup label="' . $category . '">';
foreach ($re_services as $re_serv){
if($re_serv['Catergory'] == $category)
echo '<option value="' . $re_serv['ServiceID'] . '">' . $re_serv['Service'] . '</option>';
}
echo '</optgroup>';
}
echo '</select>';
另一种选择是完全改变你的阵列结构:
foreach ($re_services as $re_serv){
$ows_Category = $re_serv->getAttribute("ows_OfferingCatType");
$ows_ServiceID = $re_serv->getAttribute("ows_Title");
$ows_Service = $re_serv->getAttribute("ows_OfferingsName_Edit");
$ows_Hours = $re_serv->getAttribute("ows_Hours");
$Service_Array[$ows_Category][]= array(
"ServiceID" => $ows_ServiceID,
"Service" => $ows_Service,
"Hours" => $ows_Hours
);
}
echo '<select>';
foreach($Service_Array as $category => $re_services){
echo '<optgroup label="' . $category . '">';
foreach($re_services as $re_serv){
echo '<option value="' . $re_serv['ServiceID'] . '">' . $re_serv['Service'] . '</option>';
}
echo '</optgroup>';
}
echo '</select>';