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 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?