3 回答
TA贡献1946条经验 获得超4个赞
您可以利用关联数组键来强制唯一性并比较价格:
<?php
// Our data
$array = [
[ 'model_id' => 1, 'price' => 2000 ],
[ 'model_id' => 2, 'price' => 3000 ],
[ 'model_id' => 1, 'price' => 1500 ]
];
// Store the final result
$result = [];
// Loop the data
foreach( $array as $v )
{
// If this model_id has not been encountered or if the price is lower than what's stored then make it the new price
if( !isset( $output[ $v[ 'model_id' ] ] ) || $v[ 'price' ] < $output[ $v[ 'model_id' ] ][ 'price' ] )
{
$output[ $v[ 'model_id' ] ] = $v;
}
}
// Get rid of the unique keys
$output = array_values( $output );
print_r( $output );
输出:
Array
(
[0] => Array
(
[model_id] => 1
[price] => 1500
)
[1] => Array
(
[model_id] => 2
[price] => 3000
)
)
TA贡献1744条经验 获得超4个赞
您可以按降序排序price,然后提取和索引,model_id以便最后一个(price每个model_id索引的最低值)将覆盖其他:
array_multisort(array_column($array, 'price'), SORT_DESC, $array);
$result = array_column($array, null, 'model_id');
TA贡献1802条经验 获得超5个赞
您可以使用 usort 数组函数获取第一个最小值记录,然后使用临时数组并运行 foreach 函数来删除重复记录。
下面的代码对我来说工作正常。
<?php
$arr = array(
[
'model_id' => 1,
'price' => 2000
],
[
'model_id' => 2,
'price' => 3000
],
[
'model_id' => 1,
'price' => 1500
]
);
usort($arr, function ($a, $b) {
return $a['price'] - $b['price'];
});
$input = $arr;
$temp = array();
$keys = array();
foreach ( $input as $key => $data ) {
unset($data['price']);
if ( !in_array($data, $temp) ) {
$temp[] = $data;
$keys[$key] = true;
}
}
$output = array_intersect_key($input, $keys);
print_r($output);
- 3 回答
- 0 关注
- 156 浏览
添加回答
举报