0

我有一个XML由第三方提供的,我无法控制它的格式。它看起来像这样:

<base>  
    <results index="1">  
        <quote vendor_name="Company X">  
            <quote_detail rate="3.375" price="-0.440">  
                <stuff>value</stuff>  
            </quote_detail>  
        </quote>  
    </results>  
    <results index="2">  
        <quote vendor_name="Company y">  
            <quote_detail rate="3.548" price="-0.230">  
                <stuff>value</stuff>  
            </quote_detail>  
        </quote>  
    </results>  
    <results index="3">  
        <quote vendor_name="Company Z">  
            <quote_detail rate="3.799" price="1.120">  
                <stuff>value</stuff>  
            </quote_detail>  
        </quote>  
    </results>  
</base>

我需要做的是返回价格最接近于零的结果 (vendor_namerate)price而不超过上下两个。理想的结果看起来像这样(中间的最接近零):

  1. Z公司 / 3.875 / -1.375
  2. Y 公司 / 3.750 / -0.875
  3. 公司 X / 3.375 / -0.440
  4. A公司 / 3.500 / 0.250
  5. B公司 / 3.375 / 1.125

我不确定执行此操作所需的逻辑或如何XML在运行所述逻辑时保留信息。有什么帮助吗?

4

2 回答 2

0

我只是为您提供一些链接以帮助您入门。

请查看simpleXML以使用 php 对象访问 xml 数据。您评论中的 XQuery Hint 也为您指明了这个方向。

在遍历您的结果时,您可以将奖品的绝对值保存在一个数组中,并使用ksort对其进行排序。

于 2012-07-13T14:53:24.647 回答
0

您需要做的是从 XML 中解析出数据以便能够使用它。然后,一旦你有了数据,你就可以选择你需要的公司。

这是使用 PHPDOMDocument类的主要工作解决方案。首先,首先将公司解析为一个数组:

$doc = new DOMDocument;
$doc->loadXML( $xml); // $xml = your string from above

$xpath = new DOMXPath( $doc);

$companies = array();
foreach( $xpath->query('//results') as $result) {
    $quote = $xpath->query( 'quote', $result)->item(0);
    $vendor_name = $quote->attributes->getNamedItem( 'vendor_name')->value;

    $quote_detail = $xpath->query( 'quote_detail', $quote)->item(0);
    $rate = $quote_detail->attributes->getNamedItem( 'rate')->value;
    $price = $quote_detail->attributes->getNamedItem( 'price')->value;

    $companies[] = array( 
        'vendor_name' => $vendor_name,
        'rate' => $rate,
        'price' => $price
    );
}

var_dump( $companies);

现在,您有一个公司数组,类似于:

array(3) {
  [0]=>
  array(3) {
    ["vendor_name"]=>
    string(9) "Company X"
    ["rate"]=>
    string(5) "3.375"
    ["price"]=>
    string(6) "-0.440"
  }
  [1]=>
  array(3) {
    ["vendor_name"]=>
    string(9) "Company y"
    ["rate"]=>
    string(5) "3.548"
    ["price"]=>
    string(6) "-0.230"
  }
  [2]=>
  array(3) {
    ["vendor_name"]=>
    string(9) "Company Z"
    ["rate"]=>
    string(5) "3.799"
    ["price"]=>
    string(5) "1.120"
  }
}

然后,对价格字段中的公司列表进行排序。

usort( $companies, function( $a, $b) { 
    if( $a['price'] == $b['price']) 
        return 0; 
    return $a['price'] < $b['price'] ? -1 : 1;
});

var_dump( $companies);

您的示例数据已经排序,所以这最终什么都不做。但是,您需要一个排序数组才能确定哪些最接近于零。

从这里开始,您将不得不弄清楚如何选择您需要的 5 个元素。我认为这不仅仅是开始所需要的。

于 2012-07-13T15:04:41.757 回答