【发布时间】:2013-12-22 14:58:48
【问题描述】:
我必须保留以下数组结构,因为它是现有网站:
$label_options = array(
"label_size" => 'A4',
"label_position" => 'Top',
"label_qty" => 50
);
$ink_options = array(
"black" => 1,
"colour" => 0
);
$item = array(
"item_number" => 12546518,
"item_type" => 'Canon',
"item_label_options" => $label_options,
"item_ink_options" => $ink_options,
"item_qty" => 2,
"item_price" => 13.99,
"item_total" => 26.98,
"item_delivery" => 2.49
);
if (isset($_SESSION['cart'])) {
$_SESSION['cart'][$unique] = $item;
} else {
$_SESSION['cart'] = array($unique => $item);
}
我现在希望能够输出数组内的值和数组内的数组。我可以使用以下内容:
foreach ($_SESSION['cart'] as $unique => $item) {
print 'Item Number = '.$item['item_number'].'<br />';
print 'Qty = '.$item['item_qty'].'<br />';
print 'Price = '.$item['item_price'].'<br />';
foreach ($item['item_label_options'] as $key => $option) {
print $option['label_size'].'<br />';
print $option['label_position'].'<br />';
print $option['label_qty'].'<br />';
}
}
它成功输出了第一个循环,但没有输出第二个循环——只输入每个循环的第一个字母:
Item Number = 12546518
Qty = 1
Price = 7.99
A // should be A4
T // should be Top
5 // should be 50
还有一种方法可以让我循环并输出所有值,而无需实际编写'Item Number = ... 它可以只输出每个键及其值,因为我并不总是知道每个键有多少以及每个键的名称是什么?
【问题讨论】:
标签: php arrays loops multidimensional-array foreach