大家好,我需要帮助整理偶数和奇数。数字以表格形式输入,并被调用到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);
你想要的是
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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句