You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP开发问题:将$tsp值均分至count>0的count字段循环出错

均匀分配$tsp值到数组符合条件的count字段

需求

将变量$tsp的值均匀分配到数组$fin中所有**"count"字段值大于0**的元素的"count"字段上。

初始代码

$tsp = 9;
$fin = [
    "1701" => ["total_space" => 0, "count" => 0],
    "1702" => ["total_space" => 0, "count" => 0], 
    "1703" => ["total_space" => 20, "count" => 20], 
    "1704" => ["total_space" => 28, "count" => 28]
];

期望结果

$tsp = 9;
$fin = [
    "1701" => ["total_space" => 0, "count" => 0],
    "1702" => ["total_space" => 0, "count" => 0], 
    "1703" => ["total_space" => 20, "count" => 25], // +5
    "1704" => ["total_space" => 28, "count" => 32] // +4
];

问题代码(错误实现)

原代码错误地给每个符合条件的字段都加了9,代码如下:

for ($i = $tsp; $i > 0; $i--) {
    foreach ($fin as $dt => $s) {
        if ($s['count'] > 0) {
            $fin[$dt]['count'] = $s['count'] + 1;
            $tsp = $tsp - 1;
        }
    }
}

正确实现方法

核心思路是先统计有效元素数量,再计算基础分配值和余数,最后完成分配:

$tsp = 9;
$fin = [
    "1701" => ["total_space" => 0, "count" => 0],
    "1702" => ["total_space" => 0, "count" => 0], 
    "1703" => ["total_space" => 20, "count" => 20], 
    "1704" => ["total_space" => 28, "count" => 28]
];

// 筛选出count>0的元素,统计数量
$validItems = array_filter($fin, function($item) {
    return $item['count'] > 0;
});
$validCount = count($validItems);

if ($validCount > 0 && $tsp > 0) {
    // 计算每个元素的基础分配值,以及剩余无法均分的数量
    $baseAdd = intdiv($tsp, $validCount);
    $remainder = $tsp % $validCount;
    
    // 遍历数组完成分配
    foreach ($fin as $key => &$item) {
        if ($item['count'] > 0) {
            $item['count'] += $baseAdd;
            // 余数部分依次给前几个有效元素各加1
            if ($remainder > 0) {
                $item['count'] += 1;
                $remainder--;
            }
        }
    }
}

// 查看结果
print_r($fin);

代码解释

  1. 用array_filter过滤出count>0的元素,统计出有效元素的数量$validCount。
  2. 用intdiv计算每个有效元素能分到的基础值$baseAdd,用取模运算得到余数$remainder(也就是无法均分的部分)。
  3. 遍历数组时,先给每个有效元素加上基础值,剩下的余数依次给前几个有效元素各加1,这样就能保证分配尽可能均匀,和期望结果一致。

内容的提问来源于stack exchange,提问作者Termate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 22:35:22