开发者

php loop array and update

开发者 https://www.devze.com 2023-04-13 09:49 出处:网络
I have an array and I wish to update the values in roomTotalPrice. However when I loop, it changes to just a variable.

I have an array and I wish to update the values in roomTotalPrice. However when I loop, it changes to just a variable.

Array I want to change:

Array
(
    [10] => Array
        (
            [开发者_如何学JAVA12] => 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
                )

        )

Code I am using:

//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
                )

        )


Use this code:

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

Anyway this code is based on the fact that $iroom['roomTotalPrice'] loop on the right sub-array as you have written.


Are you trying to make the sum for prices ?

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


Assuming that the $iroom variable is the array in your first code sample, I believe you can use the following code to set all 'roomTotalPrice' entries to 100:

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


Is this what your want?

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
    }
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号