foreach循环中的多数组使用

时间:2013-01-04 13:26:42

标签: php

我在$ _SESSION

中存储了以下数组
[Bookings] => Array
    (
        [date] => Array
             (
                [0] => 1/12/2013
                [1] => 1/19/2013
                [2] => 2/03/2013
            )

        [price] => Array
            (
                [0] =>  100
                [1] =>  150
                [2] =>  120
             )

   )

但是我想使用foreach循环并对数组中的两个值执行计算。我似乎无法理解如何使用foreach来容纳多值,我有一个foreach的样本我写的以下是我想要实现的目标。任何人都指出了我正确的方向。

foreach ($_SESSION['Bookings'] as $bookings) 
{
   myDate = $bookings[date];
   myPrice = $bookings[price];

   // Some other stuff here
}

3 个答案:

答案 0 :(得分:3)

foreach ($_SESSION['Bookings']['date'] as $key => $value) {
    $myDate = $value;
    $myPrice = $_SESSION['Bookings']['price'][$key];
}

我想更简单:)

答案 1 :(得分:2)

foreach (array_keys($_SESSION['Bookings']['date']) as $key) 
{
    $myDate  = $_SESSION['Bookings']['date'][$key];
    $myPrice = $_SESSION['Bookings']['price'][$key];
}

应该有用吗?

有关array_keys

的一些信息

答案 2 :(得分:0)

直接遍历您的子数组并从其他

中读取相应的值
foreach ( $_SESSION['Bookings'][ 'date' ] as $key => $myDate) {

    $myPrice = $_SESSION['Bookings'][ 'price' ][ $key ];


    // here you can access to $myDate and $myPrice

    // Some other stuff here
}