codeigniter 如何比较数组中的值php [duplicate]

jhkqcmku  于 2022-12-07  发布在  PHP
关注(0)|答案(2)|浏览(132)

此问题在此处已有答案

PHP Find the Index of the highest key value(1个答案)
上个月关门了。
数组中有数据

[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 } ?>
sczxawaw

sczxawaw1#

<?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循环中使用该索引存储它的索引,这样我们就可以达到预期的结果

vbkedwbf

vbkedwbf2#

这将首先计算列表中的最大'nilai'值,然后在array_map中为列表中的每一项创建一个带有额外键'max'的列表副本。该值将根据nihai是否等于$maxNilai而被设置为'true'或'false'。然后您可以使用'max'布尔值来选择是否将其着色为绿色。

$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
        )

)

相关问题