Cakephp 3:view.ctp求和两个变量
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Cakephp 3:view.ctp求和两个变量相关的知识,希望对你有一定的参考价值。
我有一个视图,显示一个相关的收入数组。我在控制器中创建了一个集合来隔离我需要添加在一起并显示为货币的两个变量。
public function view($id = null)
{
$annualOperatingBudget = $this->AnnualOperatingBudgets->get($id, [
'contain' => ['Azinstitutions', 'BudgetExpenses', 'BudgetExpenses.ExpenseTitles', 'BudgetRevenues', 'BudgetRevenues.RevenueTitles']
]);
$collection = new Collection($annualOperatingBudget->budget_revenues);
$revenuesGroup1 = $collection->match(['revenue_title.revenue_group' => 1 ]);
$revenuesGroup2 = $collection->match(['revenue_title.revenue_group' => 2 ]);
$tuitionAndFees = $collection->match(['revenue_title.revenue_title' => 'Tuition and Fees']);
$lessScholarshipAllowance = $collection->match(['revenue_title.revenue_title' => '- less Scholarship Allowance']);
$this->set(compact('annualOperatingBudget', $annualOperatingBudget,'revenuesGroup1', 'revenuesGroup2', 'tuitionAndFees', 'lessScholarshipAllowance'));
}
我可以使用调试工具包查看变量:
annualOperatingBudget (array)
revenuesGroup1 (array)
revenuesGroup2 (array)
tuitionAndFees (array)
4 (App\Model\Entity\BudgetRevenue)
id 5
annual_operating_budget_id 1
revenue 1278
revenue_title_id 5
revenue_title (array)
lessScholarshipAllowance (array)
5 (App\Model\Entity\BudgetRevenue)
id 6
annual_operating_budget_id 1
revenue -257
revenue_title_id 6
revenue_title (array)
我想将两个“收入”加在一起
我试过了:
<?= $this->Number->currency(
($tuitionAndFees->revenue) + ($lessScholarShipAllowance->revenue),
'USD', ['places' => 1])
?>
但是我得到了几个错误:
Notice (8): Undefined property: Cake\Collection\Iterator\FilterIterator::$revenue [ROOT\plugins\Twit\src\Template\AnnualOperatingBudgets\view.ctp, line 49]
Notice (8): Undefined variable: lessScholarShipAllowance [ROOT\plugins\Twit\src\Template\AnnualOperatingBudgets\view.ctp, line 49]
Notice (8): Trying to get property of non-object [ROOT\plugins\Twit\src\Template\AnnualOperatingBudgets\view.ctp, line 49]
答案
如果您在视图中需要的是所有学费和费用的总和,您可以使用
$tuitionAndFees = $collection
->match(['revenue_title.revenue_title' => 'Tuition and Fees'])
->sumOf('revenue');
这将仅返回匹配项的总和。为$lessScholarShipAllowance
做类似的事情,然后在你看来,简单地说
$this->Number->currency($tuitionAndFees + $lessScholarShipAllowance,
'USD', ['places' => 1])
另一答案
在尝试获取收入属性之前,您必须迭代$ tuitionAndFees和$ less ScholarShip Allowance。像这样的东西:
foreach($tuitionAndFees as $tuitionAndFee){
echo $tuitionAndFee->revenue
}
以上是关于Cakephp 3:view.ctp求和两个变量的主要内容,如果未能解决你的问题,请参考以下文章