2017-10-20 42 views
1

我遇到了一個問題,我想回顯三個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

回答

0

我的建議是排序首先使用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 
//  ) 
//) 
相關問題