从3维数组中回收选定的单个值

时间:2016-02-25 04:45:35

标签: php arrays

我希望能够使用foreach()循环来回应'来自三维数组的单个值。

以下是数组的设置方式:

$_SESSION['cart']: Array
(
    [ZL] => Array
        (
            [mID] => ZL
            [mtitle] => Zoolander 2
            [mday] => Wednesday
            [mtime] => 6:00pm
            [seat] => Array
                (
                    [sa] => 1
                    [sp] => 1
                    [sc] => 2
                    [b1] => 1
                )

            [price] => $125.00
        )

)

我可以使用以下内容打印每个键和每个值:

<div>
    <?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 } ?>
</div>

但我的一些价值仅用于处理,我不希望它们在页面上可见。

我也希望能够提供更具描述性的内容。

我将如何获得与此类似的输入:

Movie Title: Zoolander  ## [mtitle]
Day: Wednesday          ## [mday]
Time: 6:00pm            ## [mtime]

Ticket Type:

Adult: 12               ## [sa]
Pensioner: 1            ## [sp]
Child: 2                ## [sc]
Bean Bag: 1             ## [b1]

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

这应该有效:

<div>
    <?php foreach ($_SESSION['cart'] as $movie) { ?>
    <div>Movie Title: <?php echo $movie['mtitle'];?></div>
    <div>Day: <?php echo $movie['mday'];?></div>
    <div>Time: <?php echo $movie['mtime'];?></div>

    <p>Ticket Type:</p>

    <div>Adult: <?php echo $movie['seat']['sa'];?></div>
    <div>Pensioner: <?php echo $movie['seat']['sp'];?></div>
    <div>Child: <?php echo $movie['seat']['sc'];?></div>
    <div>Bean Bag: <?php echo $movie['seat']['b1'];?></div>
    <?php } ?>
</div>

输出:

Movie Title: Zoolander 2
Day: Wednesday
Time: 6:00pm

Ticket Type:

Adult: 1
Pensioner: 1
Child: 2
Bean Bag: 1

答案 1 :(得分:0)

这样的事情:

<?php
$test['ZL']['mID'] = 'ZL';
$test['ZL']['mtitle'] = 'Zoolander 2';
$test['ZL']['mday'] = 'Wednesday';
$test['ZL']['mtime'] = '6:00pm';
$test['ZL']['seat']['sa'] = 1;
$test['ZL']['seat']['sp'] = 1;
$test['ZL']['seat']['sc'] = 2;
$test['ZL']['seat']['b1'] = 1;
$test['ZL']['price'] = '$125.00';

?>
<div>
    <?php foreach ($test as $movie) { ?>
    <section>

        <ul>
            <li>Movie Title: <?php echo $movie['mtitle'];?></li>
            <li>Day: <?php echo $movie['mday'];?></li>
            <li>Time: <?php echo $movie['mtime'];?></li>
            <li>Ticket Type:</li>
            <li>Adult: <?php echo $movie['seat']['sa'];?></li>
            <li>Pensioner: <?php echo $movie['seat']['sp'];?></li>
            <li>Child: <?php echo $movie['seat']['sc'];?></li>
            <li>Bean Bag: <?php echo $movie['seat']['b1'];?></li>
        </ul>

    </section>
    <?php } ?>
</div>