情况相当复杂,请做好准备,
这是过滤器之前的数组结果
Array
(
[0] => Array
(
[pointText] => 1000pts
[points] => 1000
[redeemMode] => 1
)
[1] => Array
(
[pointText] => 950pts
[points] => 950
[redeemMode] => 1
)
[2] => Array
(
[pointText] => 800pts + Cash RM 200
[points] => 800
[redeemMode] => 2
)
[3] => Array
(
[pointText] => 500pts + Installment RM 100 (5% | 12 Months)
[points] => 500
[redeemMode] => 3
)
)
我需要检查redeemMode是否具有多于1个相同的值,我将只显示foreach结果中的最低点。在上面的示例中,redeemMode => 1似乎不止一次出现,我不想显示具有相同redeemMode的两个点,我只想显示最低点。在这种情况下,我会显示点=>仅950点。其余的redeemMode => 2和3将保持相同。
这是过滤器后的数组结果
Array
(
[0] => Array
(
[pointText] => 950pts
[points] => 950
[redeemMode] => 1
)
[1] => Array
(
[pointText] => 800pts + Cash RM 200
[points] => 800
[redeemMode] => 2
)
[2] => Array
(
[pointText] => 500pts + Installment RM 100 (5% | 12 Months)
[points] => 500
[redeemMode] => 3
)
)
答案 0 :(得分:3)
考虑一下。这些项目被放入一个由兑换模式键入的数组中。如果该密钥已经存在,则检查哪个密钥值最低,以决定保留哪一个。
$items = array(
array(
'pointText' => '1000pts',
'points' => '1000',
'redeemMode' => '1'
),
array(
'pointText' => '950pts',
'points' => '950',
'redeemMode' => '1'
),
array(
'pointText' => '800pts + Cash RM 200',
'points' => '800',
'redeemMode' => '2'
),
array(
'pointText' => '500pts + Installment RM 100 (5% | 12 Months)',
'points' => '500',
'redeemMode' => '3'
),
);
$itemsByRedeemMode = array();
foreach ($items as $item) {
if (isset($itemsByRedeemMode[$item['redeemMode']])) {
if ($item['points'] < $itemsByRedeemMode[$item['redeemMode']]['points']) {
$itemsByRedeemMode[$item['redeemMode']] = $item;
}
} else {
$itemsByRedeemMode[$item['redeemMode']] = $item;
}
}
print_r($itemsByRedeemMode);
答案 1 :(得分:0)
我的同事试图提供帮助,这是他的解决方案
<?php
$array = array(
array
(
'pointText' => '1000pts',
'points' => 1000,
'redeemMode' => 1
),
array
(
'pointText' => '950pts',
'points' => 1050,
'redeemMode' => 1
),
array
(
'pointText' => '800pts + Cash RM 200',
'points' => 800,
'redeemMode' => 2
),
array
(
'pointText' => '500pts + Installment RM 100 (5% | 12 Months)',
'points' => 500,
'redeemMode' => 3
)
);
$result = array();
foreach ($array as $data) {
$isHas = 0;
$mode = $data['redeemMode'];
foreach ($result as $key=> $data1) {
if ($data1['redeemMode'] == $mode) {
if ($data['points'] < $data1['points']) {
unset($result[$key]);
array_push($result,$data);
}
$isHas = 1;
}
}
if ($isHas == 0) {
array_push($result,$data);
}
}
print_r($result);
?>
它的工作!感谢我的同事!
答案 2 :(得分:0)
一个小阵列减少使得这个非常紧凑:
$array = array_reduce($array, function (array $result, array $item) {
if (!isset($result[$item['redeemMode']]) || $item['points'] < $result[$item['redeemMode']]['points']) {
$result[$item['redeemMode']] = $item;
}
return $result;
}, []);