【问题标题】:Symfony2 fixing array to string errorSymfony2 修复数组到字符串错误
【发布时间】:2015-04-24 21:07:30
【问题描述】:

我创建了一个计算项目总价格的树枝扩展函数:

public function getTotal($items)
    {
    $total = array();
    foreach($items as $item){
        $total[] = $item->getPrice() - $item->getDiscount() + $item->getValue();
    }
    return $total;
    }

但是,当我显示它们时,我得到 error: array to string conversion

我是这样显示的:

{{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;
    }

【问题讨论】:

  • 您返回一个数组$totals,稍后您将尝试打印该数组。也许您可以不使用数组,而是执行以下操作:$total += ...
  • 你好。我想要的是单独显示每个产品的总价格,这就是我需要一个数组的原因。如果我这样做 += 它只会打印所有产品的总和
  • 为什么不在你的产品实体中添加一个方法,比如“getTotalPrice()”,它会总结项目的折扣和价值?

标签: php symfony twig


【解决方案1】:

您的代码正在返回一个数组。

我假设你想要:

  • 返回一个数组中的每个总计:price - discount + value 每个项目。
    在这种情况下,您需要修复显示功能以从数组中获取每个总数并打印出来。例如

.

function print_totals($totals){
    foreach ($totals as $total){
       echo $total;
    } 
}

很难从您的问题中准确说出您要做什么,因为您的“显示”调用 getTotalTax(product) 其中产品似乎是单个项目,但您粘贴的功能称为 getTotal()假设数组为$items

您可能希望像这样更新每个项目的属性:

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;
}

【讨论】:

    【解决方案2】:

    您确实返回了一个数组,并且无法将其转换为字符串。例如,具体取决于您想要什么,您可以返回

    return print_r($totals, true);
    

    否则,您可以从 HTML 模板中提取单个元素并输出这些元素。

    【讨论】:

    • 您能详细解释一下 HTML 模板部分吗?
    • getToalTax 为您提供数组。不,您可以从此数组中获取所需的值,例如 {{ getTotalTax(product)["price"] }}
    猜你喜欢
    • 2013-06-23
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    相关资源
    最近更新 更多