i have data in array
[list] => Array
(
[0] => Array
(
[id] => 216
[name] => item A
[nilai] => 0.456
)
[1] => Array
(
[id] => 217
[name] => item B
[nilai] => 0.999
)
)
here I want to make a condition if the value is the largest then the text is green how to make the condition in foreach ?
this my code
<?php foreach($res['method']['list'] as $key=>$row) { ?>
<div >
<input type="radio" name="flexRadioDefault" id="flexRadioDefault1">
<label for="flexRadioDefault1"><?php echo $row['nilai'] ?></label>
</div>
<?php } ?>
CodePudding user response:
<?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 >
<input type="radio" name="flexRadioDefault" id="flexRadioDefault1">
<?php if ($key == $hightestValueIndex[0]){ ?>
<label style="color:green;" for="flexRadioDefault1"><?php echo $row['nilai'] ?></label>
<?php} else { ?>
<label for="flexRadioDefault1"><?php echo $row['nilai'] ?></label>
</div>
<?php } } ?>
In the above code we at first extract the 'nilai' in separate and find max value and store it's index using that index in foreach loop we can achieve the desired result
CodePudding user response:
This will first calculate the maximum 'nilai' value in your list, and then in array_map a copy of your list will be created with an additional key 'max' for each item in your list. This value will be set to 'true' or 'false' depending on nihai being equal to $maxNilai or not. You then can use that 'max' boolean value to color in green or not.
$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);
Output:
Array
(
[0] => Array
(
[id] => 216
[name] => item A
[nilai] => 0.456
[max] =>
)
[1] => Array
(
[id] => 217
[name] => item B
[nilai] => 0.999
[max] => 1
)
)