【问题标题】:multiple ternary operators in wordpress/phpwordpress/php 中的多个三元运算符
【发布时间】:2019-12-15 06:02:36
【问题描述】:

我正在编写如下所示的 php 代码:

$special_reports = new \WP_Query([
    'post_type' => 'cpac-special-report',
    'orderby' => 'menu_order',
    'order' => 'ASC',
    'posts_per_page' => $data->{"toggle_status"} == 3 ? 2 : 4,
    'posts_per_page' => $data->{"toggle_multi_status"} == 1 ? 3 : 4,
    'posts_per_page' => $data->{"toggle_multi_status"} == 2 ? 1 : 4,
    'posts_per_page' => $data->{"toggle_multi_status"} == 3 ? 2 : 4,
    'posts_per_page' => $data->{"toggle_multi_status"} == 4 ? 3 : 4
]);

我想最小化上面的 php 代码并使用多个三元运算符。这是 我尝试过,但我没有得到想要的 o/p。

$special_reports = new \WP_Query([
    'post_type' => 'cpac-special-report',
    'orderby' => 'menu_order',
    'order' => 'ASC',
    'posts_per_page' => $data->{"toggle_multi_status"} == 1 ? 3 : $data->{"toggle_multi_status"} == 2 ? 1 : $data->{"toggle_multi_status"} == 3 ? 2 : $data->{"toggle_multi_status"} == 4 ? 1:4
]);

问题陈述:

我想知道我应该在上面尝试过的 php 代码中进行哪些更改,以便何时,

$data->{"toggle_multi_status"} == 1 then it should print 3
$data->{"toggle_multi_status"} == 2 then it should print 1
$data->{"toggle_multi_status"} == 3 then it should print 2
$data->{"toggle_multi_status"} == 4 then it should print 3

【问题讨论】:

标签: php wordpress ternary-operator


【解决方案1】:

你应该用括号括起来:

$special_reports = new \WP_Query([
        'post_type' => 'cpac-special-report',
        'orderby' => 'menu_order',
        'order' => 'ASC',
        'posts_per_page' => $data->{"toggle_multi_status"} == 1 ? 3 : 
                             ($data->{"toggle_multi_status"} == 2 ? 1 : 
                               ($data->{"toggle_multi_status"} == 3 ? 2 : 
                                 ($data->{"toggle_multi_status"} == 4 ? 1:4)))
    ]);

【讨论】:

  • 这仍然很难阅读,我认为 if/else if 是可以的,但是嵌套了这么多 ternany 运算符使代码非常不可读。也许您应该使用另一种方法来检查 $data->{"toggle_multi_status"} 值,例如 switch
猜你喜欢
  • 2011-07-11
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
相关资源
最近更新 更多