![](/img/trans.png)
[英]Laravel 6 - How to get the value from controller's compact array in view/blade?
[英]How to sum data in array of JSON that get from controller when we compact to the view (Laravel)
我正面临一个问题。 在下面给出的 JSON 数组中:
$results = [
{
proj_name: rental,
act_name: income,
amount: "1000"
},
{
proj_name: rental,
act_name: expend,
amount: "-2000"
},
{
proj_name: rental,
act_name: initiall,
amount: "3000"
},
{
proj_name: rental,
act_name: income,
amount: "4000"
},
{
proj_name: rental,
act_name: expend,
amount: "-5000"
},
{
proj_name: rental,
act_name: initial,
amount:"6000"
},
{
proj_name: loan,
act_name: income,
amount: "7000"
},
{
proj_name: loan,
act_name: expend,
amount: "-8000"
},
{
proj_name: loan,
act_name: initial,
amount: "9000"
},
{
proj_name: loan,
act_name: income,
amount: "10000"
},
{
proj_name: loan,
act_name: expend,
amount: "-11000"
},
{
proj_name: loan,
act_name: initial,
amount:"12000"
}
]
我们可以在这里看到我们有两个proj_name
作为rental
和loan
。
此外,交易进一步分为income
、 expend
和initial
3 项活动。
我的问题是如何遍历$results
数组来计算上面列出的每种交易类型的总和。 我希望输出是这样的:
|------------------|
| rental |
|------------------|
|income : 5000 |
|expend : -7000 |
|initial : 9000 |
|------------------|
|Sum Rental: 7000 |
|------------------|
|
|------------------|
| loan |
|------------------|
|income : 17000 |
|expend : -19000 |
|initial : 21000 |
|------------------|
|Sum Loan: 19000 |
|------------------|
假设 JSON 数组已被解码为$json
,以下应该可以工作。
$output = [];
foreach ($json as $item) {
if (!isset($output[$item->proj_name])) {
$output[$item->proj_name] = [
'income' => 0,
'expend' => 0,
'initial' => 0,
'total' => 0
];
}
$output[$item->proj_name][$item->act_name] += $item->amount;
}
foreach ($output as $type) {
$type['total'] = $type['initial'] + $type['income'] - $type['expend'];
}
它可能需要一些小的调整,但这应该遍历您的 JSON 数组并通过任何匹配的项目增加每个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.