PHP数组零除了一个,提取该值

时间:2012-12-01 07:39:30

标签: php arrays

我有一个数组,其值随时会发生变化。它通常看起来像这样:

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 )

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

7 个答案:

答案 0 :(得分: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;
}

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

答案 1 :(得分: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 
}

答案 2 :(得分: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 
}

答案 3 :(得分:0)

$ array ='your array';

function Find($ 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 = Find($ array);

答案 4 :(得分: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...";
}

?>

答案 5 :(得分:0)

只是为了好玩:P

$array = array_flip(array_flip($array));
sort($array);
if (count($array) > 2) moreThanOne();
else onlyOne($array[1]);

答案 6 :(得分:0)

过滤数组,如果只有一个使用current()来获取它:

if(count($n = array_filter($array)) == 1) {
    execute_command(current($n));
} else {
    execute_command();
}