我需要將變數$tsp均勻地添加到"count"欄位中的值中,但僅限于那些"count"大于 0 的欄位中。
$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;
}
}
}
uj5u.com熱心網友回復:
您嘗試實作的問題是您遍歷陣列中的所有條目并為每個. 您只想增加其中一個,而不是全部...$fin $tsp
這將是一個可能的解決方案:
<?php
$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]
];
while ($tsp > 0) {
array_walk($fin, function(&$s) use (&$tsp) {
if ($tsp > 0 && $s['count'] > 0) {
$s['count'] ;
$tsp--;
}
});
}
print_r($fin);
輸出顯然是:
Array
(
[1701] => Array
(
[total_space] => 0
[count] => 0
)
[1702] => Array
(
[total_space] => 0
[count] => 0
)
[1703] => Array
(
[total_space] => 20
[count] => 25
)
[1704] => Array
(
[total_space] => 28
[count] => 32
)
)
uj5u.com熱心網友回復:
與其在重新檢查 0 個計數的回圈中使用單個增量和減量來強制算術,不如使用一種時間復雜度較低的技術,該技術永遠不會重新訪問 0 個計數行。
我的代碼片段過濾了一次陣列,然后只為符合條件的行添加了一次值。
代碼:(演示)
$qualifiers = array_filter($fin, fn($row) => $row['count']);
$divideBy = count($qualifiers);
foreach ($qualifiers as $id => $row) {
$tsp -= $toAdd = ceil($tsp / $divideBy);
--$divideBy;
$fin[$id]['count'] = $toAdd;
}
var_export($fin);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/514915.html
標籤:php数组整数算术
