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 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?