【问题标题】:How to change array elements with if/else如何使用 if/else 更改数组元素
【发布时间】:2014-08-19 14:44:16
【问题描述】:

如何用 if/else 改变数组中的值?

代码:

    public function getActions()
{
    return array(
    'dislike' => array(
        'enabled' => true,
        'action_type_id' => 2,
        'phrase' => Phpfox::getPhrase('like.dislike'),
        'phrase_in_past_tense' => 'disliked',
        'item_phrase' => 'comment',
        'item_type_id' => 'feed',
        'table' => 'feed_comment',
        'column_update' => 'total_dislike',
        'column_find' => 'feed_comment_id',
        'where_to_show' => array('', 'photo')           
        )
    );
}

如何使用 if/else 插入更改代码?

if (Phpfox::isMobile())
    {
        'phrase' => Phpfox::getPhrase('mobiletemplate.unlike_icon'),
    }
else
    {
        'phrase' => Phpfox::getPhrase('like.dislike'),
    }

谢谢你的帮助!

【问题讨论】:

  • 'phrase' => Phpfox::getPhrase(Phpfox::isMobile() ? 'mobiletemplate.unlike_icon' : 'like.dislike')
  • 感谢@putvande 的回复!

标签: php arrays if-statement phpfox


【解决方案1】:

你可以通过使用三元运算符来解决这个逻辑问题:

'phrase' => Phpfox::isMobile() ? Phpfox::getPhrase('mobiletemplate.unlike_icon') : Phpfox::getPhrase('like.dislike'),

【讨论】:

    【解决方案2】:

    使用三元运算符进行内联检查:

    public function getActions()
    {
        return array(
        'dislike' => array(
            'enabled' => true,
            'action_type_id' => 2,
            'phrase' => Phpfox::getPhrase(
                Phpfox::isMobile()
                ? 'mobiletemplate.unlike_icon'
                : 'like.dislike'
            ),
            'phrase_in_past_tense' => 'disliked',
            'item_phrase' => 'comment',
            'item_type_id' => 'feed',
            'table' => 'feed_comment',
            'column_update' => 'total_dislike',
            'column_find' => 'feed_comment_id',
            'where_to_show' => array('', 'photo')           
            )
        );
    }
    

    【讨论】:

    • 非常感谢您的回复!
    【解决方案3】:

    更简单,但仅适用于这种情况:

    'phrase' => Phpfox::getPhrase(Phpfox::isMobile()? 'mobiletemplate.unlike_icon' : 'like.dislike'),
    

    【讨论】:

    • 谢谢你!感谢你!感谢你! =D
    【解决方案4】:

    像这样的

    'phrase' => call_user_func(function(){ 
       if(Phpfox::isMobile()){
          return Phpfox::getPhrase('mobiletemplate.unlike_icon');
       }else{
          return Phpfox::getPhrase('like.dislike');
       }
     }), ...
    

    【讨论】:

    • 为什么要向数组中添加匿名函数?
    • 对不起,大家为什么这么着急?这不是比赛!恕我直言,匿名函数比三元运算符更灵活。
    • 感谢您回答我的问题!
    • 我要求你们所有人删除自己的反对票。我的代码完美地回答了这个问题,并展示了解决这个问题的另一种方法。您的反对意见是基于一个小错误代码 - 在一分钟内修复 - 现在已经过时了。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多