PHP:SOAP响应排序结果

时间:2016-07-02 13:29:56

标签: php soap

我正试图通过ROOMPRICE对肥皂回应的结果进行排序:

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

1 个答案:

答案 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";
}