php - 多维关联数组上的 foreach 循环

标签 php arrays multidimensional-array foreach

我有一个数组 ($this->taxBand),它有 3 个键 => 值对。每个值都是另一个数组:

array(3) {
  ["basic"]=>
  array(3) {
    ["rate"]=>
    int(20)
    ["start"]=>
    int(0)
    ["end"]=>
    int(31865)
  }
  ["higher"]=>
  array(3) {
    ["rate"]=>
    int(40)
    ["start"]=>
    int(31866)
    ["end"]=>
    int(150000)
  }
  ["additional"]=>
  array(3) {
    ["rate"]=>
    int(45)
    ["start"]=>
    int(150001)
    ["end"]=>
    NULL
  }
}

我不仅需要循环遍历键“basic”、“higher”和“additional”,还需要循环遍历它们内的数组。

我将把“开始”和“结束”值与另一个变量进行比较,并根据“速率”进行计算。

我已经使用我在这里找到的许多示例和官方文档以几种不同的方式尝试了嵌套 foreach,并且只能让它返回“基本”数组元素。

示例:

foreach ($this->taxBand as $key => $band) {

            foreach ($band as $subKey => $value) {

                    // Do my stuff

            }

        }

如果我返回 $band,我会得到:

array(5) {
  ["rate"]=>
  int(20)
  ["start"]=>
  int(0)
  ["end"]=>
  int(31865)
}

$key 返回:

string(5) "basic"

我正在清除缺少一些非常基本的东西,并且没有完全理解如何正确循环这些数组并获取我需要的所有数据。

任何帮助将不胜感激。 :)

编辑:尝试展示我计划如何使用此循环的示例。由于其他函数/变量,这很困难:

foreach ($this->taxBand as $key => $band) {

                    if ($band["end"] !== null || $band["end"] > 0) {
                        $band["amount"] = $this->get_lower_figure($this->totalTaxableAmount, $band["end"]) - $bandDeductions;
                    } else {
                        $band["amount"] = $this->totalTaxableAmount - $bandDeductions;
                    }

                $band["percentage_amount"] = ($band["amount"] / 100) * $band["rate"];
                $totalDeduction += $band["percentage_amount"];
                $bandDeductions += $band["amount"];

                return $totalDeduction;

        }

假设 $this->totalTaxableAmount 为 40000,则“percentage_amount”应返回浮点值 6373,对于基本带,它确实如此。但它也应该从较高的频段返回 3254。

get_lower_figure() 仅接受两个参数并检查哪个参数小于另一个参数。

最佳答案

您似乎一切都正确......但是如果您要直接使用start/end/rate值,您不需要第二个 foreach 循环。像这样的事情应该可以让你继续:

$values = array();
foreach($this->taxBand as $key => $band) {
    $calculation = ($band['end'] - $band['start']) / $band['rate'];

    $values[$key] = $calculation;
}
return $values;

我怀疑这是否是您计划做的工作,但重点是您可以直接访问内部关联数组$band

如果您出于某种原因要使用子循环,您可以执行以下操作:

foreach($this->taxBand as $key => $band) {
    // Set variables for this band

    foreach($band as $subKey => $value) {
        switch($subKey) {
             case 'start': // do something
                 break;
             case 'end': // do something
                 break;
             case 'rate': // do something
                 break;
        }
    }

    // Calculations finished
}

关于php - 多维关联数组上的 foreach 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22815511/

相关文章:

php - 使用 session 用户 ID 将数据插入数据库的正确行

php - 多个表单和多个提交,一个提交按钮

C++ int a[n] 在 g++ 中工作但在 vs2008 中不工作

c++ - 查找输入数字以了解它在数组中的位置

python - 计算二维数组中跨维度的平均值

java - 如何从两个一维数组创建二维数组并执行计算

c - 返回一个数组

php - 如何动态生成自创建页面?

php - 谷歌地图 api3 错误

c++ - 尝试使用 while 循环将数据从文件读入数组。还必须检查以确保第一个也是唯一的值不是 -1