php - 如何在codeigniter中显示数据数组?
问题描述
我正在开发一个带有会话的购物车。我已将表单数据输入控制器并创建了一个数组以传递给会话。
if($this->input->get()) {
//get form data
$pizza = $this->input->get('pizza');
$size = $this->input->get('size');
$toppings = $this->input->get('topping');
$sides = $this->input->get('side');
$amount = $this->input->get('amount');
//get list of toppings
if ($toppings) {
foreach ($toppings as $topping) {
$slug = $topping;
$toppinglist = $this->toppingmodel->get_topping($slug);
}
}
else{
$toppinglist = NULL;
}
//get list of slides
if ($sides) {
foreach ($sides as $side) {
$slug = $side;
$sidelist = $this->sidemodel->get_side($slug);
}
}
else{
$sidelist = NULL;
}
//create order array
$orderList = array(
'pizza' => $pizza,
'size' => $size,
'toppings' => $toppinglist,
'sides' => $sidelist,
'amount' => $amount
);
//add array to sessions
if ($this->session->has_userdata('orderId')) {
$cart = $this->session->userdata('orderList');
array_push($cart, $orderList);
$this->session->set_userdata('orderList', $cart);
} else {
$uniqueId = uniqid();
$cart = array($orderList);
$this->session->set_userdata('orderId', $uniqueId);
$this->session->set_userdata('orderList', $orderList);
}
}
然后我将该数组传递给数据数组以传递给视图。
$data['cartitems'] = $this->session->userdata('orderList');
这是我使用 print_r 时得到的示例输出数组。这个数组中有两个订单。
Array
(
[cartitems] => Array
(
[0] => Array
(
[pizza] => Meat Delight
[size] => 450.00
[toppings] => Array
(
[id] => 2
[slug] => cheese
[toppingName] => Extra Cheese
[price] => 75.00
)
[sides] => Array
(
[id] => 1
[sideName] => Chicken Wings
[price] => 400.00
[slug] => chicken-wing
)
[amount] => 1
)
[1] => Array
(
[pizza] => Meat Delight
[size] => 800.00
[toppings] => Array
(
[id] => 3
[slug] => peppers
[toppingName] => Green Peppers
[price] => 60.00
)
[sides] => Array
(
[id] => 1
[sideName] => Chicken Wings
[price] => 400.00
[slug] => chicken-wing
)
[amount] => 1
)
)
)
如何在视图中循环遍历此数组以显示购物车?数据数组被发送到视图$this->load->view('pages/cart', $data);
我创建订单数组的方式是否错误?谢谢你。
编辑:我正在循环查看数组,
<?php foreach ($cartitems as $cartitem) : ?>
<?php foreach ($cartitem['toppings'] as $topping) : ?>
<h5>Item Name</h5>
<p> <?php echo $cartitem['pizza']?> - Price = <?php echo $cartitem['size']?></p>
<p> Toppings - <?php echo $topping['price'] ?> </p>
<?php endforeach; ?>
<?php endforeach; ?>
当我尝试访问浇头时,我被抛出一个错误,说Message: Illegal string offset 'price'
有人能告诉我这是为什么吗?
解决方案
推荐阅读
- xslt-2.0 - XSLT 2.0 xsl:result-document 每 n 个元素
- azure-cosmosdb - Gremlin 查询中的引用属性
- javafx - 多个 Text 对象(在 JavaFX 中)可以同时设置它们的样式吗?
- macos - 无法使用终端将文件夹复制到特定位置 - Mac
- mysql - 如何将 R 连接到 MySQL?无法连接到数据库:错误:无法加载插件缓存_sha2_password
- c++ - 如何知道在这种情况下要编译什么?
- c# - 查询 System.Xml.Linq.XElement 中的元素
- python - 如何使用配置文件更改 Flask 服务器主机/端口?
- laravel - 存储在 laravel 上的奇怪问题
- ibm-doors - 传递给跳过列表的空参数