dshyu6866 2011-10-14 00:00
浏览 16
已采纳

php循环数组得到总数

I am having some difficulty looping through an array and calculating fields. Here is the array $iroom:

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

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

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

   [price] => 178
)

I want to (adults*prices)+(adults*$asup)+(chidern*$csup)+$ssup and pu the answer into the roomTotalPrice. So far the outer forloop sets the roomTotalPrice price but I cannot get the inner loops to calculate the price. The $sup are extra supplement prices.

The code I got so far:

                        foreach($iroom['roomTotalPrice'] as &$irt){
                            foreach($iroom['adults'] as $ira){

                            }
                            $irt = ;
                        }
  • 写回答

1条回答 默认 最新

  • duandai2178 2011-10-14 00:36
    关注

    CODE WRAPPED IN FUNCTION, TO HANDLE NEW ARRAY FORMAT

    /*
      Note that this function may not be 100% correct. I notice you have removed
      the 'supp' key from the array, and that your current spec doesn't do anything
      with the 'price' key. I suspect you may want the line
    
        + ((isset($array['supp'])) ? $array['supp'] : 0);
    
      to read
    
        + ((isset($array['price'])) ? $array['price'] : 0);
    
    */    
    
    function calculateTotalPrices ($array, $asup = 10, $csup = 10) {
      if (!is_array($array) || !isset($array['num_rooms']) || !$array['num_rooms']) return FALSE; // make sure data is valid
      for ($i = 0; $i < $array['num_rooms']; $i++) { // Loop num_rooms times
        $array['roomTotalPrice'][$i] =
          ((isset($array['adults'][$i],$array['prices'][$i])) ? ($array['adults'][$i] * $array['prices'][$i]) + ($array['adults'][$i] * $asup) : 0) // Calculate price for adults
          + ((isset($array['childern'][$i])) ? ($array['childern'][$i] * $csup) : 0) // Calculate price for children
          + ((isset($array['supp'])) ? $array['supp'] : 0); // Add the supplement
      }
      // Get a total price for adults + children + supplements for all rooms
      $array['grandTotal'] = array_sum($array['roomTotalPrice']);
      return $array;
    }
    
    $iroom = array (
      'num_rooms' => 2,
      'adults' => array (
        0 => 2,
        1 => 3
      ),
      'childern' => array (
        0 => 1,
        1 => 2
      ),
      'prices' => array (
        0 => 44.5,
        1 => 44.5
      ),
      'price' => 178,
    );
    
    print_r(calculateTotalPrices($iroom));
    /* With the above array, outputs
    Array
    (
        [num_rooms] => 2
        [adults] => Array
            (
                [0] => 2
                [1] => 3
            )
    
        [childern] => Array
            (
                [0] => 1
                [1] => 2
            )
    
        [prices] => Array
            (
                [0] => 44.5
                [1] => 44.5
            )
    
        [price] => 178
        [roomTotalPrice] => Array
            (
                [0] => 119
                [1] => 183.5
            )
    
        [grandTotal] => 302.5
    )
    */
    
    print_r(calculateTotalPrices($iroom,20,25));
    /* With your sample array, outputs
    Array
    (
        [num_rooms] => 2
        [adults] => Array
            (
                [0] => 2
                [1] => 3
            )
    
        [childern] => Array
            (
                [0] => 1
                [1] => 2
            )
    
        [prices] => Array
            (
                [0] => 44.5
                [1] => 44.5
            )
    
        [price] => 178
        [roomTotalPrice] => Array
            (
                [0] => 154
                [1] => 243.5
            )
    
        [grandTotal] => 397.5
    )
    */      
    

    CODE UPDATED WITH ADDITIONAL CHECKS

    foreach ($iroom as $k1 => $v1) { // Loop outer array
      if (is_array($v1)) { // Make sure element is an array
        foreach ($v1 as $k2 => $v2) { // Loop inner array
          if (is_array($v2)) { // Make sure element is an array
            for ($i = 0; $i < $v2['num_rooms']; $i++) { // Loop num_rooms times
              $iroom[$k1][$k2]['roomTotalPrice'][$i] =
                ((isset($v2['adults'][$i],$v2['prices'][$i])) ? ($v2['adults'][$i] * $v2['prices'][$i]) + ($v2['adults'][$i] * $asup) : 0) // Calculate price for adults
                + ((isset($v2['childern'][$i])) ? ($v2['childern'][$i] * $csup) : 0) // Calculate price for children
                + $v2['supp']; // Add the supplement
            }
            // Get a total price for adults + children + supplements for all rooms
            $iroom[$k1][$k2]['grandTotal'] = array_sum($iroom[$k1][$k2]['roomTotalPrice']);
          }
        }
      }
    }
    
    print_r($iroom);
    

    EDIT

    Using the exact code above, feeding in the array above, and setting $asup = $csup = 10; at the top, I get no errors, and this output:

    Array
    (
        [10] => Array
            (
                [12] => Array
                    (
                        [num_rooms] => 2
                        [adults] => Array
                            (
                                [0] => 2
                                [1] => 3
                            )
    
                        [childern] => Array
                            (
                                [0] => 1
                                [1] => 2
                            )
    
                        [prices] => Array
                            (
                                [0] => 44.5
                                [1] => 44.5
                            )
    
                        [price] => 178
                        [supp] => 0
                        [roomTotalPrice] => Array
                            (
                                [0] => 119
                                [1] => 183.5
                            )
    
                        [grandTotal] => 302.5
                    )
    
            )
    
    )
    

    Note that the first result comes out at 119, not 129 as you state in the comment above - this is because in your example array, supp is 0 and not 10, as you have used in your calculation.

    I have also tested with more complex arrays (with more elements at the first and second levels) and it works fine.

    I'm guessing if you are getting "invalid argument supplied for foreach" errors it's because in your actual array, you highest level has some non-array memebers. This can easily be overcome by changing

    foreach ($v1 as $k2 => $v2) {
    

    to

    if (is_array($v1)) foreach ($v1 as $k2 => $v2) {
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 哪个tomcat中startup一直一闪而过 找不出问题
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳