我已经看到了这么多重复的问题。真的很抱歉重复的问题。但没有找到正确的解决方案或可能没有得到正确的逻辑。我已经使用了usort()来实现这些目的。 我有以下数组。
Array
(
[0] => stdClass Object
(
[id] => 808
[ScreenName] => Dispatch
[OriginalName] => First Unit on Scene
[OriginalPrintName] => First Unit on Scene
[CurrentName] => Blank
)
[1] => stdClass Object
(
[id] => 809
[ScreenName] => Dispatch
[OriginalName] => EMS Agency
[OriginalPrintName] => EMS Agency
[CurrentName] => Blank
)
[2] => stdClass Object
(
[id] => 597
[ScreenName] => Dispatch
[OriginalName] => Date
[OriginalPrintName] => Date
[CurrentName] => Date
)
[3] => stdClass Object
(
[id] => 509
[ScreenName] => Dispatch
[OriginalName] => Incident #
[OriginalPrintName] => Incident #
[CurrentName] => Incident #
)
[4] => stdClass Object
(
[id] => 758
[ScreenName] => Dispatch
[OriginalName] => Run# /Call #
[OriginalPrintName] => Run#
[CurrentName] => Run Call
)
)
使用以下条件
if (($y2->CurrentName == "") || ($y2->CurrentName == "Blank")) {
print $y2->OriginalName ;
} else {
print $y2->CurrentName ;
}
在列表中,打印所有CurrentName但是
如果currenName为空,则打印OriginalName
像这样的东西。
Date
Incident #
Run Call
Type Of Service Req
Complaint Reported
Response Urgency
Location Type
Address Type
Address
Address Cont
我想将这些列表显示为albhabetically sort。 我的usort()函数是
usort($yvals, function ($elem1, $elem2) {
if (($elem1->CurrentName == "" || $elem1->CurrentName == "Blank") && ($elem2->OriginalName == "" || $elem2->OriginalName == "Blank")) {
return strcmp($elem1->OriginalName, $elem2->OriginalName);
}else if(($elem1->CurrentName != "" || $elem1->CurrentName != "Blank") && ($elem2->CurrentName == "") || ($elem2->CurrentName == "Blank")){
return strcmp($elem1->CurrentName, $elem2->OriginalName);
}else{
return strcmp($elem1->CurrentName, $elem2->CurrentName);
}
});
它在某个地方工作,但不适合所有人。
答案 0 :(得分:0)
尝试strcasecmp代替strcmp ...
答案 1 :(得分:0)
这可能不是最优的,但我在某些情况下迭代php中的对象的经验会产生反直觉的结果,为了简单起见,我会将排序与您想要一次性实现的过滤分开。 另外,将对象托管到工作类并将名称检索移动到方法将是很好的编程实践。
class SomeWorkingClass{
public function getProperName(){
// proper name retrieval functionality
}
}
usort($yvals, function ($elem1, $elem2) {
return strcmp($elem1->getProperName(), $elem2->getProperName());
}