3 回答

TA貢獻1846條經驗 獲得超7個贊
我認為使用基本的 foreach 循環可能會相當簡單。
如果你看到這個數組,它是按價格從低到大排列的。
所以,我假設你的價格已經排序,額外的排序是多余的。
您可以循環并維護遇到的不同價格的數量。一旦$cnt達到4,您就可以停止收集數據并打印結果。
<?php
$cnt = 0;
$result = [];
foreach($arr as $index => $data){
if($index === 0 || $data['price'] > $arr[$index-1]['price']){
$cnt++;
}
if($cnt === 4) break;
$result[] = $data;
}
echo "<pre>";
print_r($result);

TA貢獻1830條經驗 獲得超9個贊
這是一種相當手動的方法,它從數據中提取價格并在過濾器中使用它...
$items = array(
array( 'id' => 104, 'book_id' => 32, 'price' => 55 ),
array( 'id' => 117, 'book_id' => 76, 'price' => 65 ),
array( 'id' => 135, 'book_id' => 77, 'price' => 65 ),
array( 'id' => 100, 'book_id' => 78, 'price' => 65 ),
array( 'id' => 101, 'book_id' => 21, 'price' => 85 ),
array( 'id' => 107, 'book_id' => 35, 'price' => 90 ),
array( 'id' => 108, 'book_id' => 64, 'price' => 90 ),
array( 'id' => 130, 'book_id' => 101, 'price' => 100 ),
);
// extract unique prices out of the data
$prices = array_unique( array_column( $items, 'price' ) );
// sort the prices (ascending)
sort( $prices );
// extract three prices
$threePrices = array_slice( $prices, 0, 3 );
// filter the items that have a price in the lowest three prices array
$lowestItems = array_filter( $items, function( $item ) use ( $threePrices ) {
return in_array( $item['price'], $threePrices );
});
print_r( $lowestItems );
// Array
// (
// [0] => Array
// (
// [id] => 104
// [book_id] => 32
// [price] => 55
// )
//
// [1] => Array
// (
// [id] => 117
// [book_id] => 76
// [price] => 65
// )
//
// [2] => Array
// (
// [id] => 135
// [book_id] => 77
// [price] => 65
// )
//
// [3] => Array
// (
// [id] => 100
// [book_id] => 78
// [price] => 65
// )
//
// [4] => Array
// (
// [id] => 101
// [book_id] => 21
// [price] => 85
// )
//
// )
- 3 回答
- 0 關注
- 162 瀏覽
添加回答
舉報