[英]Show only 3 posts and sorting by price with foreach loop
我遇到了一个问题,我想按for-each回显三个fullBookingURL
和price
。 我的条件示出的3个数据,其price
是阵列中最低,然后显示,最低price
的价格
array (size=19)
0 =>
object(stdClass)[3820]
public 'agencyName' => string 'ZenHotels.com' (length=13)
public 'fullBookingURL' => string 'http://example.com' (length=25)
public 'price' => int 590
public 'tax' => int 0
2 =>
object(stdClass)[3826]
public 'agencyName' => string 'ZenHotels.com' (length=13)
public 'fullBookingURL' => string 'http://example.com' (length=25)
public 'price' => int 591
public 'tax' => int 0
5 =>
object(stdClass)[3835]
public 'agencyName' => string 'Hotellook' (length=9)
public 'fullBookingURL' => string 'http://example.com' (length=25)
public 'price' => int 606
public 'tax' => int 0
6 =>
object(stdClass)[3838]
public 'agencyName' => string 'ZenHotels.com' (length=13)
public 'fullBookingURL' => string 'http://example.com' (length=25)
public 'price' => int 712
public 'tax' => int 0
7 =>
object(stdClass)[3841]
public 'agencyName' => string 'ZenHotels.com' (length=13)
public 'fullBookingURL' => string 'http://example.com' (length=25)
public 'price' => int 713
public 'tax' => int 0
我的密码
foreach($sval2->rooms as $bookingurl){
echo $bookingurl->fullBookingURL;
echo $bookingurl->price;
}
我的建议是先使用uasort
对项目进行排序,然后使用array_slice
获取前n
元素(在您的情况下为3个元素)。
<?php
// prepare some test data
$a = new \stdClass();
$a->url = 'first_url';
$a->price = 1;
$b = new \stdClass();
$b->url = 'second_url';
$b->price = 2;
$c = new \stdClass();
$c->url = 'third_url';
$c->price = 3;
$d = new \stdClass();
$d->url = 'third_url';
$d->price = 4;
$arr = [$d, $c, $b, $a];
// sorting elements
uasort($arr, function($a, $b) { return $a->price > $b->price; });
// printing first 3 elements
print_r(array_slice($arr, 0, 3));
// Array(
// [0] => stdClass Object
// (
// [url] => first_url
// [price] => 1
// )
// [1] => stdClass Object
// (
// [url] => second_url
// [price] => 2
// )
// [2] => stdClass Object
// (
// [url] => third_url
// [price] => 3
// )
// )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.