我正在用foreach语句输出公司列表。为了比较每家公司的第一个字母,我用每家公司的首字母代替。这些需要通过if比较器操作发送,以查看这是否是每个初始字符范围的第一次出现。var_dump显示srt_cmp已找到所需的值。当我在if对多个组合的比较中使用该值时,if语句将不会执行。
<?php
$stringCompanyListing = '<!-- beginning of business listing -->'."'n";
$countCompanies=0;
$haveStrungAD = "";
$haveStrungEI = "";
$haveStrungJO = "";
$haveStrungPU = "";
$haveStrungVZ = "";
foreach ($files as $file){
$company = new SimpleXMLElement($file, 0, true);
$COMPANYKEY[$countCompanies] = basename($file, '.xml');
if ($countCompanies >= 1){
$currentCompany = substr($COMPANYKEY[$countCompanies],0, 1);
$previousCompany = substr(($COMPANYKEY[($countCompanies-1)]),0, 1);
$checkForNavigation = strcmp($previousCompany, $currentCompany);
// var_dump at this point show intended values such as "A" and "-1"
if ($haveStrungAD == ""){
if ($currentCompany == range("A", "D")){
if ($checkForNavigation <= -1){
$stringCompanyListing .= ' <div class="categoryHeading"><a name="atod"></a>A-D</div>';
$haveStrungAD = "done";
}
}
}
if ($haveStrungEI == ""){
if ($currentCompany == range("E", "I")){
if ($checkForNavigation <= -1){
$stringCompanyListing .= ' <div class="categoryHeading"><a name="etoi"></a>E-I</div>';
$haveStrungEI = "done";
}
}
}
// more if comparisons omitted
}
$countCompanies++;
}
既然你在一个数组($COMPANYKEY)中有所有的公司名称,你就不能使用usort()或uasort()对数组进行排序吗(取决于你是否需要键来保持与值的连接)。然后在数组中循环,并将公司分配给相应的数组。例如,
uasort($COMPANYKEY, function ($a, $b) {
return $a < $b;
});
foreach ($COMPANYKEY AS $comp)
{
$char = substr($comp, 0, 1); //get first letter
if ($char <= 'd')
$atod[] = $comp;
elseif ($char > 'd' && $char <= 'm')
$etom[] = $comp;
}
您可以编写附加条件,将其加载到公司的附加数组中,也可以在$char上使用switch语句并编写一系列案例。无论哪种方式,都应该加载每个。
此外,如果您正在使用代码,则不需要使用==运算符,而需要使用inarray()函数。range返回一个值数组,因此您需要检查您的值是否为该数组,而不是等于数组。
希望这能有所帮助。