2014-09-02 56 views
0

我试图计算使用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 
?> 

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

回答

3

使用array_filter然后count

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

这个伟大的工程,非常感谢:) – RustyIngles 2014-09-02 09:37:19

+0

@xdazz u能解释这个'函数($ VAL)使用($ params)方法' – 2014-09-02 09:40:40

+1

@Prashant http://php.net /manual/functions.anonymous.php – xdazz 2014-09-02 09:42:18

0

更好地将它们添加到阵列

$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; 
} 
0

您可以设置各种社会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

0

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

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