2

我有一个值不时变化的数组。它通常看起来像这样:

Array ( [0] => 0 [1] => 0 [2] => 9876 [3] => 0 [4] => 0 [5] => 0 [6] => 0 [7] => 0 [8] => 0 [9] => 0 [10] => 0 [11] => 0 )

除 1 外,所有值均为 0(索引位置将更改)。如果多个值大于 0,我需要执行特定的命令。否则,如果只有一个值大于 0,我需要获取该值并将其传递给特定命令。

4

7 回答 7

3

创建一个仅包含非空值的新数组。array_filter没有回调将返回所有不评估为的元素FALSE。:

$a = array(...);
$values = array_filter($a);

switch(count($values)) {
  case 0: echo 'All 0!'; break;
  case 1: specificCommandWithValue($values[0]); break;
  default: executeSpecificCommand(); break;
}

如果你有 false-y 值,你想保留 ( FALSE, NULL, '0', ''),传递一个回调来进行严格的值比较:function($el) { return $el !== 0; }

于 2012-12-01T07:46:48.770 回答
1

尝试

$count  =0;
foreach($array as $item){

   if($item !=0){
      $count = $count+1;
    }
}
if($count > 1){

//execute a specific command
}elseif($count == 1){
  // take that value and pass it to a specific command
}else{
  //all value are zero 
}
于 2012-12-01T07:41:16.250 回答
0

这是@NullPointer 的答案,但我添加了一个变量来保存“那个值”。

$count  =0;
$nonzero = null;
foreach($array as $item){

   if($item !=0){
      $count = $count+1;
      $nonzero = $item;
    }
}
if($count > 1){

//execute a specific command
}elseif($count == 1){
  specific_command($nonzero);
}else{
  //all value are zero 
}
于 2012-12-01T07:48:43.440 回答
0

$array = '你的数组';

函数查找($数组){

 $count = 0;
 $needle = -1;                
 foreach($array as $item){
         if($item > 0){
               $count++;
               $needle = $item;
         } 
         if($count > 1)
                return -1; //error as number of non-zeroes greater than 1
 }
 if($count > 0)
      return $needle;  //returns the required single non-zero item
 return 0; // returns zero if nothing is found

}

$return = 查找($array);

于 2012-12-01T08:06:04.130 回答
0

试试这个代码。

<?PHP

$array = array(
"1" => "0",
"2" => "0",
"3" => "0",
"4" => "24",
"5" => "0");

$zero_plus_keys = 0;
$zero_plus_val  = array();

foreach($array as $key => $val)
{
    if($val > 0)
    {
        $zero_plus_keys++;
        $zero_plus_val = array($key,$val);
    }
}

if($zero_plus_keys == 1)
{
    echo "In array '".$zero_plus_val[0]."' key contains Greater than zero value. the value is = '".$zero_plus_val[1]."'";
}
elseif($zero_plus_keys > 1)
{
    echo "More keys Greater than zero(0)";
}
else
{
    echo "All keys contains zero(0)s only...";
}

?>
于 2012-12-01T08:32:02.420 回答
0

只是为了好玩:P

$array = array_flip(array_flip($array));
sort($array);
if (count($array) > 2) moreThanOne();
else onlyOne($array[1]);
于 2012-12-01T08:33:47.523 回答
0

过滤数组,如果只有一种用途current()可以得到它:

if(count($n = array_filter($array)) == 1) {
    execute_command(current($n));
} else {
    execute_command();
}
于 2016-05-24T14:26:12.400 回答