你好有办法在laravel或php中获得两个foreach的区别。这是我的示例代码
@foreach($budgets as $budget)
$budget->b_amount
@endforeach
@foreach($purchases as $purchase)
$purchase->p_amount
@endforeach
所以基本上我需要得到每个foreach的所有值,然后取各自的差异。有没有办法做到这一点?像这样......
<?php
$diff = $budget->b_amount - $purchase->p_amount;
?>
非常感谢你。
答案 0 :(得分:1)
@if(count($budgets) == count($purchases))
@foreach($budgets as $key => $value)
$diff[] = $budgets[$key]->b_amount - $purchases[$key]->p_amount
@endforeach
@endif
现在$diff
包含一系列差异。
答案 1 :(得分:0)
首先,如果你能确保数组中的所有对象都是数值,你可以使用下面的函数:
function diff($budgets, $purchases) {
$b = 0;
$p = 0;
foreach ($budgets as $budget) {
$b += $budget;
}
foreach ($purchases as $purchase) {
$p += $purchase;
}
return $b-$p;
}
此外,如果你只需要忽略+/-符号:
function diff($budgets, $purchases) {
$b = 0;
$p = 0;
foreach ($budgets as $budget) {
$b += $budget;
}
foreach ($purchases as $purchase) {
$p += $purchase;
}
return abs($b-$p);
}
但是,如果您不确定数值是否在数组中:
function diff($budgets, $purchases) {
$b = 0;
$p = 0;
foreach ($budgets as $budget) {
$b += is_numeric($budget)?$budget:0;
}
foreach ($purchases as $purchase) {
$p += is_numeric($purchase)?$purchase:0;
}
return $b-$p;
}