我在回答一个多维数组时遇到了一些困难。
这是数组转储:
$_SESSION['cart']: Array
(
[SW] => Array
(
[mID] => SW
[mday] => Mon
[mtime] => 9:00pm
[seat] => Array
(
[sa] => 8
[sp] => 5
[sc] => 2
[b2] => 3
)
[price] => $200.00
)
)
这是我的回声循环:
<?php foreach ($_SESSION['cart'] as $booking) { ?>
<section>
<?php foreach ($booking as $key => $value) { ?>
<ul>
<li>
<label><?php echo $key ?>:</label>
<span><?php echo $value?></span>
</li>
</ul>
<?php } ?>
</section>
<?php } ?>
当循环到达[座位]时,我一直遇到错误。
如何让它循环嵌套数组?
感谢您的帮助!
答案 0 :(得分:0)
试试这个:
<?php foreach ($_SESSION['cart'] as $booking) { ?>
<section>
<?php foreach ($booking as $bookingValue) { ?>
<ul>
<li>
<?php if(is_array($bookingValue)) {
foreach ($bookingValue as $key => $value) { ?>
<label><?php echo $key ?>:</label>
<span><?php echo $value?></span>
<?php }
} else { ?>
<label><?php echo $key ?>:</label>
<span><?php echo $value?></span>
<?php } ?>
</li>
</ul>
<?php } ?>
</section>
<?php } ?>
答案 1 :(得分:0)
这是一个回显数组中每个项目的函数,即使它包含其他数组。您需要检查$value
是否为数组。
function echoArrayValues($array) {
foreach ($array as $key => $value) {
if(is_array($value)) {
echoArrayValues($value);
continue;
}
echo $value.'<br>';
}
}
答案 2 :(得分:0)
您无法回显数组。 echo
需要一个字符串。
如果值是数组,则再次循环。
<?php foreach ($_SESSION['cart'] as $booking) { ?>
<section>
<?php foreach ($booking as $key => $value) { ?>
<ul>
<li>
<?php if(is_array($value)) {
foreach($value as $k=>$v){
echo $k." > ".$v."<br/>";
}
} else { ?>
<label><?php echo $key ?>:</label>
<span><?php echo $value?></span>
<?php } ?>
</li>
</ul>
<?php } ?>
</section>
<?php } ?>
答案 3 :(得分:0)
试试这个:
<?php foreach ($_SESSION['cart'] as $booking) { ?>
<section>
<?php foreach ($booking as $key => $value) { ?>
<ul>
<li>
<?php if( $key == 'seat' ) {
foreach($value as $seat_key => $seat_value) {
}
} else { ?>
<label><?php echo $key ?>:</label>
<span><?php echo $value?></span>
}?>
</li>
</ul>
<?php } ?>
</section>
<?php } ?>
答案 4 :(得分:0)
array_walk_recursive($_SESSION['cart'], function($value, $key) { echo $key . ' ' . $value . PHP_EOL; })
输出:
mID SW
mday Mon
mtime 9:00pm
sa 8
sp 5
sc 2
b2 3
price $200.00
答案 5 :(得分:-1)
像这样的东西
<?php foreach ($_SESSION['cart'] as $booking) { ?>
<section>
<?php foreach ($booking as $key => $value) { ?>
<ul>
<li>
<?php if(is_array($value)) {
foreach($value as $k=>$v){
echo $k." : ".$v."<br/>";
}
} else { ?>
<label><?php echo $key ?>:</label>
<span><?php echo $value?></span>
<?php } ?>
</li>
</ul>
<?php } ?>
</section>
<强>输出强>
mID: SW
mday: Mon
mtime: 9:00pm
sa : 8
sp : 5
sc : 2
b2 : 3
price: $200.00