我有一个像这样的数组列表
[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] => 110
[book_id] => 21
[price] => 85
)
[5] => Array
(
[id] => 107
[book_id] => 35
[price] => 90
)
[6] => Array
(
[id] => 108
[book_id] => 64
[price] => 90
)
[7] => Array
(
[id] => 130
[book_id] => 101
[price] => 100
)
如果您看到该数组,则按照price
从最低到最大的顺序排列。我正在尝试重新排列阵列,以仅获得3个最低价格,并过滤掉其余价格。意味着,当我进行过滤时,我的数组必须包含55-85之间的价格,该价格来自索引0-4。
有没有办法像我这样过滤呢?谢谢。
这是一种相当手动的方法,可以从数据中提取价格并将其用于过滤器中...
$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
// )
//
// )
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句