只显示3个帖子,并按照foreach循环的价格排序

问题描述:

我遇到了一个问题,我想回显三个fullBookingURLprice by for each。我的条件示出的3个数据,其price是阵列中最低,然后显示,最低price价格只显示3个帖子,并按照foreach循环的价格排序

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; 
} 
+0

是否必须使用foreach?您可以首先使用带自定义回调函数的'uasort'对数组中的项目进行排序,然后回显排序数组的前3项。 –

+0

@ kaduev13不,它不是强制性的吗? – Syn00123

+0

你面临的问题是什么? – kerbholz

我的建议是排序首先使用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 
//  ) 
//)