php循环数组和更新

时间:2011-10-13 21:42:58

标签: php arrays

我有一个数组,我希望更新roomTotalPrice中的值。但是当我循环时,它只会变为变量。

我想改变的数组:

Array
(
    [10] => Array
        (
            [12] => Array
                (
                    [num_rooms] => 2
                    [adults] => Array
                        (
                            [0] => 2
                            [1] => 2
                        )

                    [prices] => Array
                        (
                            [0] => 44.5
                            [1] => 44.5
                        )

                    [roomTotalPrice] => Array
                        (
                            [0] => 44.5
                            [1] => 44.5
                        )

                    [price] => 178
                    [supp] => 0
                )

        )

我正在使用的代码:

//Total Room Price
foreach($iroom['roomTotalPrice'] as $irt){
    $s_rate[$iraid][$iroid]['roomTotalPrice'] = 100;
}



Array
(
    [10] => Array
        (
            [12] => Array
                (
                    [num_rooms] => 2
                    [adults] => Array
                        (
                            [0] => 2
                            [1] => 2
                        )

                    [prices] => Array
                        (
                            [0] => 44.5
                            [1] => 44.5
                        )

                    [roomTotalPrice] => 100
                    [price] => 178
                    [supp] => 0
                )

        )

4 个答案:

答案 0 :(得分:3)

使用此代码:

foreach($iroom['roomTotalPrice'] as &$irt){
    $irt = 100;
}

无论如何,这段代码是基于$ iroom ['roomTotalPrice']在您编写的右子阵列上循环的事实。

答案 1 :(得分:2)

您是否想要计算价格总和?

$ x [10] [12] [roomTotalPrice] = array_sum($ x [10] [12] [roomTotalPrice])

答案 2 :(得分:2)

假设$ iroom变​​量是第一个代码示例中的数组,我相信您可以使用以下代码将所有'roomTotalPrice'条目设置为100:

foreach ($iroom as $firstLevelIndex => $firstLevelArray) {
    foreach ($firstLevelArray as $secondLevelIndex => $secondLevelArray) {
        $iroom[$firstLevelIndex][$secondLevelIndex]['roomTotalPrice'] = 100;
    }
}

答案 3 :(得分:2)

这是你想要的吗?

foreach ($iroom as $k1 => $v1) { // Loop outer array
  foreach ($v1 as $k2 => $v2) if (isset($v2['roomTotalPrice'])) { // Loop inner arrays and make sure they have a roomTotalPrice key
    foreach ($v2['roomTotalPrice'] as $k3 => $v3) { // Loop roomTotalPrice array
      $iroom[$k1][$k2]['roomTotalPrice'][$k3] = 100; // Change the values
    }
  }
}