我在陣列中有資料
[list] => Array
(
[0] => Array
(
[id] => 216
[name] => item A
[nilai] => 0.456
)
[1] => Array
(
[id] => 217
[name] => item B
[nilai] => 0.999
)
)
在這里,如果值最大,則我想創建一個條件,然后文本為綠色如何在 foreach 中創建條件?
這是我的代碼
<?php foreach($res['method']['list'] as $key=>$row) { ?>
<div class="form-check">
<input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1">
<label class="form-check-label" for="flexRadioDefault1"><?php echo $row['nilai'] ?></label>
</div>
<?php } ?>
uj5u.com熱心網友回復:
<?php
$val_array = array_column($res['method']['list'], 'nilai');
$hightestValueIndex = array_keys($val_array, max($val_array));
foreach($res['method']['list'] as $key=>$row) { ?>
<div class="form-check">
<input class="form-check-input" type="radio" name="flexRadioDefault" id="flexRadioDefault1">
<?php if ($key == $hightestValueIndex[0]){ ?>
<label style="color:green;" class="form-check-label" for="flexRadioDefault1"><?php echo $row['nilai'] ?></label>
<?php} else { ?>
<label class="form-check-label" for="flexRadioDefault1"><?php echo $row['nilai'] ?></label>
</div>
<?php } } ?>
在上面的代碼中,我們首先單獨提取'nilai'并找到最大值并使用該索引在foreach回圈中存盤它的索引,我們可以獲得所需的結果
uj5u.com熱心網友回復:
這將首先計算串列中的最大 'nilai' 值,然后在 array_map 中為串列中的每個專案創建一個附加鍵 'max' 的串列副本。根據 nihai 是否等于 $maxNilai,此值將設定為“true”或“false”。然后,您可以使用該“最大”布林值以綠色或不著色。
$list = [
[ 'id' => 216, 'name' => 'item A', 'nilai' => 0.456 ],
[ 'id' => 217, 'name' => 'item B', 'nilai' => 0.999 ]
];
$maxNilai = max(array_column($list, 'nilai'));
$result = array_map(
fn($item) => array_merge($item, [ 'max' => $item['nilai'] === $maxNilai ]),
$list
);
print_r($result);
輸出:
Array
(
[0] => Array
(
[id] => 216
[name] => item A
[nilai] => 0.456
[max] =>
)
[1] => Array
(
[id] => 217
[name] => item B
[nilai] => 0.999
[max] => 1
)
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/497858.html
上一篇:Codeigniter4:在BaseBuilder上執行->findAll()時出現“嘗試讀取陣列上的屬性'name'”錯誤
