【问题标题】:PHP Array Select Random Value on RefreshPHP数组在刷新时选择随机值
【发布时间】:2017-03-30 07:21:05
【问题描述】:

我在页面上有提交按钮。一旦我每次点击它应该给出随机不同的结果。

我有以下数组代码

$qty = 10;
$array = array(4 => 2, 6 => 5, 7 => 10, 8 => 1, 10 => 5);
$array = arsort($array);
echo "<pre>";
print_r($array);
//array_rand($array);
exit;

数组对是客户和数量。我需要将$qty 与数组的最大值进行比较。如果匹配,则取出该值并打印出最终结果。

不必为每个客户分配 100% 的数量。但最终应该分配 10 个数量。

所以输出可以是

第一次点击提交按钮

Array
(
    [7] => 10
)

第二次点击提交按钮

Array
(
    [7] => 2
    [6] => 2
    [10] => 2
    [4] => 2
    [8] => 2
)

第三次点击提交按钮

Array
(
    [7] => 5
    [6] => 2
    [10] => 3
)

【问题讨论】:

    标签: php arrays sorting random


    【解决方案1】:

    我添加了内联 cmets,可能会帮助您获得:

    Demo here

    <?php
    $qty   = 10;
    $array = array(4 => 2, 6 => 5, 7 => 10, 8 => 1, 10 => 5);
    
    $final_array = [];
    
    while ($qty > 0) {
        $rand_index = array_rand($array);  // Get random customer
        $max_val    = $array[$rand_index]; // Get the maximum qty available for the customer
    
        if (!$max_val) {
            continue;
        }
    
        if ($max_val > $qty) {
            $max_val = $qty;
        }
    
        $possible_val = rand(1, $max_val); // Assign random qty to the customer but not more than allowed
    
        // Check if customer is added with qty already, if not add
        if (array_key_exists($rand_index, $final_array)) {
            $final_array[$rand_index] += $possible_val;
        } else {
            $final_array[$rand_index] = $possible_val;
        }
    
        $array[$rand_index] -= $possible_val;
        $qty -= $possible_val;
    }
    
    print_r($final_array); // Your final desired combination
    

    【讨论】:

    • 感谢您的回答。拥有 Max Qty 的客户应该获得缺少的优先权
    • Fatal error: Call to undefined function random_int()
    • 适用于 PHP 7,您可以将其替换为 rand()。也更新了答案
    • 好的,谢谢 2 件事 1] 拥有 Max Qty 的客户应该获得缺少的优先权,您可以查看一下吗? 2] 如果数组(4 => 2, 6 => 5);然后进入无限循环
    猜你喜欢
    • 1970-01-01
    • 2013-05-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 2020-11-18
    相关资源
    最近更新 更多