[英]Error while Inserting into Database an Incremented Index Value of an Array in PHP
[英]Error of index while filling an array in php
第一步是用零创建一个新数组。 这是代码:
$amounts = [];
$row = [];
for($a = 0; $a < count($receipts_with_total); $a++){
for($b = 0; $b < count($taxes); $b++){
$row[$b] = 0;
}
$amounts[] = $row;
}
然后,我继续用值填充数组。 问题是,由于某种原因,我不知道,它添加了一些索引。 下一个是填充数组的代码:
//We calculate all the taxes amounts
for($i = 0; $i < count($receipts_with_total); $i++){
$this_receipt = $receipts_with_total[$i];
//We get all the taxes for each receipt
$taxes = $this_receipt->taxes;
for($j = 0; $j < count($taxes); $j++){
$this_tax = $taxes[$j];
if($this_tax->name == "IVA 21%"){
$amounts[$i][$j] = round((($this_tax->value * $total[$i]) / 100), 2);
}
elseif($this_tax->name == "IVA 10.5%"){
$amounts[$i][$j+1] = round((($this_tax->value * $total[$i]) / 100), 2);
}
else {
$amounts[$i][$j+2] = round((($this_tax->value * $total[$i]) / 100), 2);
}
}
}
输出为:
Creacion
数组([0] =>数组([0] => 0 [1] => 0 [2] => 0)[1] =>数组([0] => 0 [1] => 0 [2] => 0)[2] =>数组([0] => 0 [1] => 0 [2] => 0)[3] =>数组([0] => 0 [1] => 0 [ 2] => 0))
Modelo
数组([0] =>数组([0] => 0 [1] => 257.46 [2] => 61.3)[1] =>数组([0] => 0 [1] => 40.36 [2] => 9.61)[2] =>数组([0] => 80.73 [1] => 40.36 [2] => 9.61)[3] =>数组([0] => 211.05 [1] => 105.53 [ 2] => 0))
Lleno
数组([0] =>数组([0] => 0 [1] => 257.46 [2] => 0 [3] => 61.3)[1] =>数组([0] => 0 [1] => 40.37 [2] => 0 [3] => 9.61)[2] =>数组([0] => 80.73 [ 1] => 0 [2] => 40.37 [4] => 9.61)[3 ] =>数组([0] => 211.05 [1] => 0 [2] => 105.53))
第一个输出是带有零的新数组。 第二个示例是带有计算数字的最终数组的的示例。 最后一个是我得到的数组。 如您所见,粗体索引代表错误。 例如,值“ 61.3”位于第一个数组的第四位,而不是第三位,这是正确的。
谢谢!
从代码中删除+1
和+2
。 只是
$amounts[$i][$j]=...
在所有情况下。
因为如果
$j=2;
在您的代码$j+1
可能变为3
我的回答只是选择您问题的一部分:
问题是,由于某种原因,我不知道,它添加了一些索引。
我猜您想始终在子数组的0索引中显示“ IVA 21”,在子数组的1索引中始终显示“ IVA 10.5”,依此类推...? 因此您不必在索引中+1或+2 ...因为$ j已经在for循环中递增了...
或者,如果您不知道哪个先出现,或者以后可能会有更多选择,请不要使用for循环。 使用php foreach并手动保持+1
$j = 0;
foreach ($taxes as $$this_tax) {
if ($this_tax->name == 'IVA 21%') {
$amounts[$i][$j] = round((($this_tax->value * $total[$i]) / 100), 2);
} elseif ($this_tax->name == 'IVA 10.5%') {
$amounts[$i][$j + 1] = round((($this_tax->value * $total[$i]) / 100), 2);
} else {
$amounts[$i][$j + 2] = round((($this_tax->value * $total[$i]) / 100), 2);
}
//myabe +3 later...
}
或者,如果您始终知道$ taxes的长度以及要放置结果的位置,为什么不只使用像0,1,2这样的静态数字。 您甚至可以创建续体,例如:
define('IVA21', 0); // const IVA21 = 0;
define('IVA105', 1);
// ... more define
//for loop starts
if ($this_tax->name == 'IVA 21%') {
$amounts[$i][IVA21] = round((($this_tax->value * $total[$i]) / 100), 2);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.