【问题标题】:Count number of variables if set to 'yes'如果设置为“是”,则计算变量数
【发布时间】:2014-09-02 09:24:10
【问题描述】:

我正在尝试使用 PHP 计算设置为“是”的变量的数量,然后输出计数。

例如,我有以下变量:

$facebook = $params->get('facebook');
$twitter = $params->get('twitter');
$email = $params->get('email');
$pinterest = $params->get('pinterest');
$google = $params->get('google');

如果它们都设置为“是”,则使用此方法将计数为 5:

<?php
    $social = array('facebook', 'twitter', 'email', 'pinterest', 'google');
    echo count($social); // output 5
?>

但是,如果有些设置为“否”,我如何计算所有设置为“是”的?

【问题讨论】:

    标签: php count


    【解决方案1】:

    使用array_filter,然后使用count

    $social = array('facebook', 'twitter', 'email', 'pinterest', 'google');
    $count = count(array_filter($social, function($val) use ($params) {
      return $params->get($val) === 'yes';
    }));
    

    【讨论】:

    • @xdazz 你能解释一下吗function($val) use ($params)
    【解决方案2】:

    最好将它们添加到数组中

    $vars['facebook'] = $params->get('facebook');
    $vars['twitter'] = $params->get('twitter');
    $vars['email'] = $params->get('email');
    $vars['pinterest'] = $params->get('pinterest');
    $vars['google'] = $params->get('google');
    

    比循环那个数组

    $count = 0;
    foreach ($vars as $var) {
        $count += strtolower($var) == 'yes' ? 1 : 0;
    }
    

    【讨论】:

      【解决方案3】:

      可以设置各种社交true的变量,如果等于'yes',则等于false,否则就相加即可。

      $facebook  = ( $params->get('Facebook')  == 'yes');
      $twitter   = ( $params->get('twitter')   == 'yes');
      $email     = ( $params->get('email')     == 'yes');
      $pinterest = ( $params->get('pinterest') == 'yes');
      $google    = ( $params->get('google')    == 'yes');
      
      $count = $facebook + $twitter + $email + $pinterest + $google;
      

      或者,如果您想使用数组,请像以前一样设置 var 然后您可以查看此答案:PHP Count Number of True Values in a Boolean Array

      【讨论】:

        【解决方案4】:

        一个简单的方法是循环然后检查每个值...

        $true = 0; //The count...
        foreach ($social as $value) {
            if ($value = "yes") { $true++; } //Checks each value if 'yes', increases count...
        }
        echo $true; //Shows the count...
        

        【讨论】:

          猜你喜欢
          • 2013-08-27
          • 2023-01-13
          • 2013-03-23
          • 2012-11-17
          • 2017-02-20
          • 2013-08-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多