dougu1990 2011-12-07 16:21
浏览 17
已采纳

数组中的PHP计算(递归?)

I'm trying to write a function that calculates the grand total price of each order, when given the price of the product and a credit that this user has. The credit should be deducted and if anything remains it should be deducted from the next order.

The function should return the final price of each order and the credits that remain foreach each account in one single array with the customer IDs as keys. Any negative numbers (credit or order prices) should all be set to 0.

'abc' and 'def' are customer IDs. This sample code should explain things much better. Do I need a recursive function for this?

Input:

//should return: order 1 = 375, order 2 = 90, remaining credit = 0;
$order['abc'][1] = 500;
$order['abc'][2] = 90;
$credit['abc'] = 125;

//should return: order 1: 0, order 2: 0, remaining credit = 125
$order['def'][1] = 100;
$order['def'][2] = 75;
$credits['def'] = 300;

The return should be one single array, as such:

$set['abc'][1] = 375;
$set['abc'][2] = 90;
$set['abc']['credit_remaining'] = 0;
$set['def'][1] = 0;
$set['def'][2] = 0;
$set['def']['credit_remaining'] = 125;
  • 写回答

3条回答 默认 最新

  • dpbf62565 2011-12-07 16:49
    关注

    No need for recursion, why not try something like this?

    $newArray = array();
    
    foreach ($order as $customer => $value) 
    {
        $newArray[$customer]['credit_remaining'] = $credit[$customer];
    
        foreach ($order[$customer] as $order_num => $cost) 
        {
            //Order is more than credit
            if($newArray[$customer]['credit_remaining'] - $order[$customer][order_num] <= 0)
            {
                $newArray[$customer][$order_num] = $order[$customer][$order_num] - newArray[$customer]['credit_remaining'];
                $newArray[$customer]['credit_remaining'] = 0;
            }
    
            //Otherwise
            else
            {
                $newArray[$customer]['credit_remaining'] -= $order[$customer][$order_num];
                $newArray[$customer][$order_num] = 0;
            }
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)