对于每个循环将无法正常工作

时间:2013-10-01 21:46:51

标签: php arrays foreach

我在弄清楚为什么每个循环都不起作用时遇到了问题。当我打印出结果时,它会根据工资数组正确显示,但是当我尝试在代码中稍后使用数据时(做工资*税),它只是做了一些而且它不会相应地循环...我很新编码所以请理解:P

<?php




$salaries =array(
635000.00, 420000.00, 260000.00, 150000.00, 550000.00, 90000.00);
foreach ($salaries as $a)
{
if ($a >= 500000) 
{$t =0.45;
echo $t;
}
else
{
if ($a>=300000 and ($a<=500000))
{$t=0.35;
echo $t;
}
if ($a>=200000 and ($a<=300000))
{$t=0.2;
echo $t;
}
if ($a>=100000 and ($a<=200000))
{$t=0.1;
echo $t;
{
if ($a>= 100000) 
{$t =0;
echo $t;    
}}}}}




?>
($salaries[0]*$t) 

工作正常,但在我对其他成员的数组中,它只是选择0.45%作为正确的税额。

2 个答案:

答案 0 :(得分:0)

尽管这段代码对于它的作用并没有多大意义,但这里有一个修复:

$salaries =array(635000.00, 420000.00, 260000.00, 150000.00, 550000.00, 90000.00);
foreach($salaries as $a)
{
    if ($a >= 500000) 
    {
        $t =0.45;
        echo $t;
    }
    elseif ($a>=300000 and ($a<=500000))
    {
        $t=0.35;
        echo $t;
    }
    elseif ($a>=200000 and ($a<=300000))
    {
        $t=0.2;
        echo $t;
    }
    elseif ($a>=100000 and ($a<=200000))
    {
        $t=0.1;
        echo $t;
    }
    else
    {
        $t =0;
        echo $t;    
    }
}

答案 1 :(得分:0)

我想你要为每一个薪水计算税金,在这种情况下(使用你的编码风格):

<?php
$salaries = array(
  635000.00,
  420000.00,
  260000.00,
  150000.00,
  550000.00,
  90000.00
);
foreach ($salaries as $salary) {
  if ($salary >= 500000) {
    $tax = 0.45;
    echo "<p>Salary: $salary x Tax: $tax = " . $salary * $tax . "</p>";
  } else {
    if ($salary >= 300000 and ($salary <= 500000)) {
      $tax = 0.35;
      echo "<p>Salary: $salary x Tax: $tax = " . $salary * $tax . "</p>";
    }
    if ($salary >= 200000 and ($salary <= 300000)) {
      $tax = 0.2;
      echo "<p>Salary: $salary x Tax: $tax = " . $salary * $tax . "</p>";
    }
    if ($salary >= 100000 and ($salary <= 200000)) {
      $tax = 0.1;
      echo "<p>Salary: $salary x Tax: $tax = " . $salary * $tax . "</p>"; {
        if ($salary <= 100000) {
          $tax = 0;
          echo "<p>Salary: $salary x Tax: $tax = " . $salary * $tax . "</p>";
        }
      }
    }
  }
}
?>

输出:

Salary: 635000 x Tax: 0.45 = 285750
Salary: 420000 x Tax: 0.35 = 147000
Salary: 260000 x Tax: 0.2 = 52000
Salary: 150000 x Tax: 0.1 = 15000
Salary: 550000 x Tax: 0.45 = 247500