偶数和奇数数字排序到文本文件中

时间:2013-11-29 10:00:52

标签: php

HI每个人都需要帮助来整理偶数和奇数。这些数字以一种形式输入并被调用到php文件(在底部)之后我需要在文本文件中显示它们这部分对我来说都很好。我无法将数字与奇数分开。我知道我们需要使用模数命令,但我不确切知道如何将它放在循环中。

    $valOne = $_GET["value1"];
    $valTwo = $_GET["value2"];
    $valThr = $_GET["value3"];
    $valFou = $_GET["value4"];
    $valFiv = $_GET["value5"];
    $valSix = $_GET["value6"];
    $valSev = $_GET["value7"];
    $valEig = $_GET["value8"];
    $valNine = $_GET["value9"];
    $valTen = $_GET["value10"];

    $myFile = "test.txt";
    $fh = fopen($myFile, 'w') or die("can't open file");
    $array1= array ($valOne, $valTwo, $valThr, $valFou,$valFiv,
                $valSix,$valSev,$valEig,$valNine,$valTen);
    foreach($array1 as $key => $value){
    fwrite($fh, $value. "\t");


    }
    fclose($fh);

3 个答案:

答案 0 :(得分:0)

你想要的是

if ($number % 2 == 0) {
    // even number
}
else
{
    // odd
}

在你的情况下

foreach($array1 as $key => $value){
    if ($value % 2 == 0) {
         fwrite($fh, $value. "\t");
    }
}

在一个文件中分隔偶数和奇数

$even = array_filter($array1, function($number) { return $number % 2 == 0; });
$odd = array_filter($array1, function($number) { return $number % 2 == 1; });

$max = max(count($even), count($odd));
for ($i = 0; $i < $max; $i++) {
    $n1 = isset($even[$i]) ? $even[$i] : "";
    $n2 = isset($odd[$i]) ? $odd[$i] : "";

    fwrite($fh, str_pad($n1, 20, STR_PAD_RIGHT) . $n2);
}

答案 1 :(得分:0)

foreach($array1 as $key => $value)
{
   $myvar = ($value %2 == 0 ? '$value' : '' );
   fwrite($fh, $myvar . "\t");
}

答案 2 :(得分:0)

尝试以下

 $valOne = $_GET["value1"];
$valTwo = $_GET["value2"];
$valThr = $_GET["value3"];
$valFou = $_GET["value4"];
$valFiv = $_GET["value5"];
$valSix = $_GET["value6"];
$valSev = $_GET["value7"];
$valEig = $_GET["value8"];
$valNine = $_GET["value9"];
$valTen = $_GET["value10"];

$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$array1= array ($valOne, $valTwo, $valThr, $valFou,$valFiv,
            $valSix,$valSev,$valEig,$valNine,$valTen);
foreach($array1 as $key => $value){
  if($value%2==0)
   {
     fwrite($fh, $value. "\t");
      }
    else
    {
      //write your own code..
       }

}
fclose($fh);