2016-07-02 74 views
0

我試圖通過SOAP響應的ROOMPRICE結果進行排序:PHP:SOAP響應排序

stdClass Object ( 
    [GetHotelsResult] => stdClass Object ( 
     [SEARCH_RESPONSE] => Array ( 
      [0] => stdClass Object ( 
       [HOTELNAME] => Hotel1 
       [ROOMNAME] => Room2 
       [ROOMPRICE] => 144.50 
      ) 
      [1] => stdClass Object ( 
       [HOTELNAME] => Hotel1 
       [ROOMNAME] => Room1 
       [ROOMPRICE] => 231.10 
      ) 
      [2] => stdClass Object ( 
       [HOTELNAME] => Hotel1 
       [ROOMNAME] => Room3 
       [ROOMPRICE] => 94.00 
      ) 
     ) 
    ) 
); 

我做了很多的解決方案,但他們沒有工作...

實際代碼:

$sClient = new SoapClient($wsdl, array('trace' => 1)); 
$response = $sClient->GetHotels($data);  
$ghdata = $sClient->__getLastResponse(); 
$doc = new DOMDocument(); 
$doc->loadXML($ghdata); 
$x = $doc->documentElement; 
$rooms = $x->getElementsByTagName("SEARCH_RESPONSE"); 
    foreach($rooms as $SEARCH_RESPONSE) 
{ // show results 
+0

好像有錯誤或你的迴應錯字:'SEARCH_RESPONSE'陣列不能有每個記錄都帶有'0'索引。 –

回答

0

假設$response是你的外stdClass對象,我想你要和錯誤這樣的:

Warning: usort() expects parameter 1 to be array, object given in ... 

這是因爲usort適用於數組而不是對象。你實際想要排序的是一個SEARCH_RESPONSE數組。另外,要注意,此數組中的元素是stdClass對象本身,所以你必須使用$a->{$key}符號代替[]

function build_sorter($key) { 
    return function ($a, $b) use ($key) { 
     // pay attention to `{$key}` notation 
     return strnatcmp($a->{$key}, $b->{$key}); 
    }; 
} 

// Get array to sort 
usort($response->GetHotelsResult->SEARCH_RESPONSE, build_sorter('ROOMPRICE')); 

foreach ($response->GetHotelsResult->SEARCH_RESPONSE as $item) { 
    echo $item->ROOMNAME . ', ' . $item->ROOMPRICE . "\n"; 
} 
+0

不錯!它工作獨立,但我試圖把我的代碼。我無法弄清楚。 (問題更新,把我的實際代碼樣本) – Arrow