Ian*_*Ian 2 php arrays foreach multidimensional-array
我有一个数组 ($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
}
}
Run Code Online (Sandbox Code Playgroud)
我不仅需要循环遍历键“basic”、“higher”和“additional”,还需要循环遍历它们内的数组。
我将把“开始”和“结束”值与另一个变量进行比较,并根据“速率”进行计算。
我已经使用我在这里找到的许多示例和官方文档以几种不同的方式尝试了嵌套 foreach ,并且只能让它返回“基本”数组元素。
例子:
foreach ($this->taxBand as $key => $band) {
foreach ($band as $subKey => $value) {
// Do my stuff
}
}
Run Code Online (Sandbox Code Playgroud)
如果我返回 $band,我会得到:
array(5) {
["rate"]=>
int(20)
["start"]=>
int(0)
["end"]=>
int(31865)
}
Run Code Online (Sandbox Code Playgroud)
$key 返回:
string(5) "basic"
Run Code Online (Sandbox Code Playgroud)
我正在清除缺少一些非常基本的东西,并且没有完全理解如何正确循环这些数组并获取我需要的所有数据。
任何帮助将非常感激。:)
编辑:尝试展示我计划如何使用此循环的示例。由于其他函数/变量,这很困难:
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;
}
Run Code Online (Sandbox Code Playgroud)
假设 $this->totalTaxableAmount 为 40000,“percentage_amount”应返回浮点值 6373,对于基本带,它确实如此。但它也应该从较高频段返回 3254。
get_lower_figure() 仅接受两个参数并检查哪个参数小于另一个参数。
您似乎一切都正确......但是如果您要直接使用//start值,则不需要第二个循环。像这样的事情应该让你继续:endrateforeach
$values = array();
foreach($this->taxBand as $key => $band) {
$calculation = ($band['end'] - $band['start']) / $band['rate'];
$values[$key] = $calculation;
}
return $values;
Run Code Online (Sandbox Code Playgroud)
我怀疑这是您计划做的工作,但重点是您可以$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
}
Run Code Online (Sandbox Code Playgroud)