我正在使用opencart。我将对象数组从控制器发送到 twig 文件。
控制器
$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' => [], // Initialize an array to hold products within this category
];
}
$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" } ] } ]
问题:
当我使用
foreach
时,它不起作用。当我打印 {crackers} 时,它会打印为上面输出的文本。下面的代码不起作用。
{% for cracker in crackers %}
<tr class='heading'>
<td colspan="5"> {{ cracker.name }}</td>
</tr>
</td>
</tbody>
</tr>
{% endfor %}
这应该有效。
$categoriesArray = array_values($categories);
// $jsonCategories = json_encode($categoriesArray, JSON_PRETTY_PRINT);
$data['crackers'] = $categoriesArray;
echo $data['crackers'];
和树枝:
{% for cracker in crackers %}
<tr class='heading'>
<td colspan="5"> {{ cracker.category_name }}</td>
</tr>
</td>
</tbody>
</tr>
{% endfor %}