You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCart中Twig模板遍历对象数组失效问题求助

问题描述

在OpenCart开发中,控制器整理好分类-商品结构的数组后,误将其转为JSON字符串传递给Twig视图,导致视图中无法用{% for %}遍历,直接输出显示为纯文本。

控制器错误代码

$data['crackers'] = [];
$results = $this->model_quickorder_order->getCrackers();

$categories = [];
foreach ($results as $row) {
    $categoryId = $row['category_id'];
    $categoryName = $row['category_name'];
    $productId = $row['product_id'];
    $productName = $row['name'];
    $specialPrice = $row['special'];
    $productPrice = $row['price'];
    $productImage = $row['product_image'];

    $product = [
        'product_id' => $productId,
        'product_name' => $productName,
        'special_price' => $specialPrice,
        'price' => $productPrice,
        'product_image' => $productImage,
    ];

    if (!isset($categories[$categoryId])) {
        $categories[$categoryId] = [
            'category_id' => $categoryId,
            'category_name' => $categoryName,
            'products' => [], // 初始化该分类下的商品数组
        ];
    }

    $categories[$categoryId]['products'][] = $product;
}

$categoriesArray = array_values($categories);
$jsonCategories = json_encode($categoriesArray, JSON_PRETTY_PRINT);
$data['crackers'] = $jsonCategories;
echo $data['crackers'];

视图输出代码(直接显示文本)

{{ crackers }}

输出结果

[ { "category_id": "67", "category_name": "Flower Pots", "products": [ { "product_id": "1", "product_name": "Flower Pots Small (10Pcs)", "special_price": "110.0000", "price": "220.0000", "product_image": "catalog/flowerpotssmall.jpg" } ] }, { "category_id": "69", "category_name": "Chakkars", "products": [ { "product_id": "2", "product_name": "Zamin Chakkar Ashoka (10 pcs)", "special_price": "150.0000", "price": "300.0000", "product_image": "catalog/Zamin_Chakkar_Asoka.jpg" } ] } ]

无法正常执行的遍历代码

{% for cracker in crackers %}
  <tr class='heading'>
    <td colspan="5"> {{ cracker.name }}</td>
  </tr>
 </td>
</tbody>
</tr>
 {% endfor %}
解决方法

方法1:修正控制器代码(推荐)

直接传递PHP数组给视图,无需转为JSON字符串。删除控制器中json_encode相关代码,把整理好的数组直接赋值给$data['crackers']:

$data['crackers'] = [];
$results = $this->model_quickorder_order->getCrackers();

$categories = [];
foreach ($results as $row) {
    $categoryId = $row['category_id'];
    $categoryName = $row['category_name'];
    $productId = $row['product_id'];
    $productName = $row['name'];
    $specialPrice = $row['special'];
    $productPrice = $row['price'];
    $productImage = $row['product_image'];

    $product = [
        'product_id' => $productId,
        'product_name' => $productName,
        'special_price' => $specialPrice,
        'price' => $productPrice,
        'product_image' => $productImage,
    ];

    if (!isset($categories[$categoryId])) {
        $categories[$categoryId] = [
            'category_id' => $categoryId,
            'category_name' => $categoryName,
            'products' => [], // 初始化该分类下的商品数组
        ];
    }

    $categories[$categoryId]['products'][] = $product;
}

// 直接传递数组,不要转JSON
$data['crackers'] = array_values($categories);
// 移除echo语句,避免提前输出内容干扰视图渲染
// echo $data['crackers'];

方法2:在Twig视图中解析JSON(不推荐)

如果无法修改控制器,可在Twig中使用json_decode过滤器将字符串转回数组,同时修正字段名错误:

{% set crackers_array = crackers|json_decode %}
{% for cracker in crackers_array %}
  <tr class='heading'>
    <td colspan="5">{{ cracker.category_name }}</td>
  </tr>
  {# 遍历分类下的商品 #}
  {% for product in cracker.products %}
    <tr>
      <td>{{ product.product_name }}</td>
      <td>{{ product.price }}</td>
      <td>{{ product.special_price }}</td>
    </tr>
  {% endfor %}
{% endfor %}

关键注意点

  • 遍历代码中字段名要匹配原数据:分类名称是category_name,不是cracker.name,需修正。
  • 控制器中必须移除echo $data['crackers'];,否则会提前输出JSON内容,破坏视图的HTML结构。

内容的提问来源于stack exchange,提问作者Maria Jeysingh Anbu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:23:20