PHP Switch statement

只谈情不闲聊 提交于 2021-01-28 08:21:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!