Php Symfony2修复数组到字符串错误
我创建了一个细枝扩展函数,用于计算项目的总价格:Php Symfony2修复数组到字符串错误,php,symfony,twig,Php,Symfony,Twig,我创建了一个细枝扩展函数,用于计算项目的总价格: public function getTotal($items) { $total = array(); foreach($items as $item){ $total[] = $item->getPrice() - $item->getDiscount() + $item->getValue(); } return $total; } 然而,当我显示它们时,我
public function getTotal($items)
{
$total = array();
foreach($items as $item){
$total[] = $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $total;
}
然而,当我显示它们时,我得到一个错误:数组到字符串的转换
我是这样展示的:
{{getTotalTax(product)}}
我试过这样做,但没有帮助:
public function getTotal($items)
{
$totals = array();
foreach($items as $item){
$totals[] = $item->getPrice() - $item->getDiscount() + $item->getValue();
if(is_array($totals)) {
return '';
}
}
return $totals;
}
您确实返回了一个数组,无法将其转换为字符串。例如,根据具体需要,您可以返回
return print_r($totals, true);
否则,您可以从HTML模板中提取单个元素并输出这些元素。您的代码将返回一个数组 我想你想: 返回数组中的每个总计:价格-折扣+每个项目的值。 在这种情况下,您需要修复显示函数,以从数组中获取每个总数并将其打印出来。例如 很难从您的问题中准确地说出您想要做什么,因为您的“显示”调用了getTotalTaxproduct,其中product似乎是单个项,但您粘贴的函数称为getTotal,它假定一个$items数组 您可能希望更新每个项目的属性,如下所示:
public function getTotal($items)
{
$total = array();
foreach($items as $item){
$item->total = $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return true;
}
或
返回总计
在这种情况下,您将需要继续添加到总数中,如下所示:
返回稍后要打印的数组$totals。也许你不需要使用数组,你可以做一些像:$total+=…Hello这样的事情。我想要的是单独显示每个产品的总价格,这就是为什么我需要一个数组。如果我做+=它只打印所有产品的总和为什么不在产品实体中添加一个方法,比如getTotalPrice,它将汇总项目的折扣和价值?你能解释更多关于HTML模板部分的信息吗?getToalTax给你数组。不,您可以从这个数组中获得所需的值,例如{{getTotalTaxproduct[price]}
public function getTotal($items)
{
$total = array();
foreach($items as $item){
$item->total = $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return true;
}
public function getTotal($items)
{
$total = 0;
foreach($items as $item){
$total += $item->getPrice() - $item->getDiscount() + $item->getValue();
}
return $total;
}