问题
switch ($sort) {
case 'abc':
$order_by = 'subject ASC';
break;
case 'fn':
$order_by = 'u.username ASC';
break;
case 'rd':
$order_by = 'p.posted_on DESC';
break;
default:
$order_by = 'p.posted_on DESC';
$sort = 'rd';
break;
}
I want to modify this little piece of code slightly I'm just not quite sure how to do it. Im pretty sure I could do it with an if else if else if, but Im assuming changing this switch would be pretty simple, but then again I'm not sure.
Anyway this is what Im trying to do, lets take the `case 'abc': for example
I want
case 'abc':
$order_by = 'subject DESC';
break;
IF
case 'abc':
$order_by = 'subject ASC';
break;
So that way, when you are sorting through records, if the sort is already using ASC, it will switch to DESC, right now my sort buttons only work one way.
TY
回答1:
switch ($sort) {
case 'abc':
$order_by = 'subject ASC';
$sort = 'cba'
break;
case 'cba':
$order_by = 'subject DESC';
$sort = 'abc'
break;
case 'fn':
$order_by = 'u.username ASC';
break;
case 'rd':
$order_by = 'p.posted_on DESC';
break;
default:
$order_by = 'p.posted_on DESC';
$sort = 'rd';
break;
}
回答2:
I would set a toggle variable:
$abcToggle = false;
//...
case 'abc':
if($abcToggle) {
// do something...
abcToggle = false;
}
else {
// do something else...
$abcToggle = true;
}
break;
Or, maybe a more succinct way:
$abcToggle = false;
//...
case 'abc':
$abcToggle ? $orderBy = 'DESC' : $orderBy = 'ASC';
$abcToggle ? $abcToggle = false : $abcToggle = true;
break;
来源:https://stackoverflow.com/questions/5739516/php-switch-statement