以下是我的代码打印:
Even numbers: 2 4 6
这是我的PHP代码:
$names = file('file.txt');
echo "Text: ";
foreach($names as $name)
{
echo $name . "</br>";
}
echo "Even numbers: ";
foreach ($names as $name) {
$name = count_chars( $name, 3);
for($i=0; $i<strlen($name);$i++) {
if (is_numeric($name[$i]) && $name[$i]%2==0)
{
echo $name[$i];
}
}
echo "<br>";
}
?>
有人能告诉我如何将所有这些值计入新行(我需要得到答案3)并获得这些值总和(我需要得到12)?我知道我必须使用计数和求和函数,我不确切知道在哪里。谢谢你的帮助。所有答案应如下所示:
Even numbers: 2 4 6
Even numbers are: 3
Even numbers sum are: 2 + 4 + 6 = 12
答案 0 :(得分:0)
试试这个:
$names = file('file.txt');
echo "Text: ";
foreach($names as $name)
{
echo $name . "</br>";
}
echo "Even numbers: ";
foreach ($names as $name) {
$count = 0
$evens = [];
$name = count_chars($name, 3);
for($i=0; $i<strlen($name);$i++) {
if (is_numeric($name[$i]) && $name[$i]%2==0)
{
$count++;
$evens[] = $name[$i];
echo $name[$i];
}
}
echo "<br>";
}
echo "Even numbers Are: " . $count;
$i=0;
foreach($evens as $e){
$i++;
if($i == count($evens)){
$evens_string .= $e . '=' ;
} else {
$evens_string .= $e . '+' ;
}
}
$even_string .= array_sum($evens);
echo "Even numbers sum are: " . $even_string;
希望这会给你一个想法!我还没有测试过代码。
答案 1 :(得分:0)
我真的不明白你的问题。
但我认为array_sum
正是你要找的。 (https://secure.php.net/manual/en/function.array-sum.php)
以下是我的代码供您参考:
$array = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
foreach($array as $key => $value) {
if (empty($value%2)) {
$even[] = $value;
} else {
$odd[] = $value;
}
}
echo 'Even numbers: '.implode(' ', $even).'<br>';
echo 'Odd numbers: '.implode(' ', $odd).'<br>';
echo 'Even numbers sum are: '.implode(' + ', $even).' = '.array_sum($even);