0

我正在尝试使用 XML 和 php 对我的产品进行排序。我想以
这样的方式在页面上显示结果:

A)首先代码可以根据我的基于字段(代码)的urisegment提取XML数据,并根据段($id)给我相关的具体产品。

B)其次,它可以在同一页面中显示属于同一类别的所有产品,而无需再次显示上述产品。

我的查询字符串如下所示: http: //myspec.com/productspec/listings/10004/EDEN%2046cmTROUGH

<?
 $list = groupBy(file_get_contents('XML/output.xml'), "WhatMoreProductSubRange");
 $id=urldecode($this->uri->segment(4)); // URL values for WhatMoreProductSubRange 
 $id2=urldecode($this->uri->segment(3)); // URL values for Code 

 foreach ($list[$id] as $product ) 
 {
  if ($id2==$product->Code)
   {
     $subcat=$product->WhatMoreProductSubRange;

  ?>
      <h1><?=$product->Name?> </h1>
<?
   }
   else { 
?>
      <h2><?=$product->Name?> </h2>
<? 
        }
}

?>
<?
  function groupBy($xml, $categoryName) {
   $xml = new \SimpleXMLElement($xml);
    $category = array();
    foreach ( $xml as $row ) {
     $attr = $row->attributes();

    if (! isset($attr->$categoryName)) {
        trigger_error("$categoryName does not exist in XML");
        break;
    }

    $category[(string) $attr->$categoryName][] = $attr;
  }
  return $category;
}
?>

XML:输出.xml

<?xml version="1.0" standalone="yes"?>
<Rows>
<Row Code="1002" Name="EDEN TROUGH  Terracotta Blue" WhatMoreProductRange="Eden"    
WhatMoreProductSubRange="EDEN 46cmTROUGH" WhatMoreWebCategory="Garden Products" />
<Row Code="1003" Name="EDEN TROUGH  Terracotta Black" WhatMoreProductRange="Eden"    
WhatMoreProductSubRange="EDEN 46cmTROUGH" WhatMoreWebCategory="Garden Products" />
<Row Code="1004" Name="EDEN TROUGH  Terracotta Orange" WhatMoreProductRange="Eden"    
WhatMoreProductSubRange="EDEN 46cmTROUGH" WhatMoreWebCategory="Garden Products" />
<Row Code="1005" Name="EDEN TROUGH  Terracotta blue" WhatMoreProductRange="Eden"    
WhatMoreProductSubRange="EDEN 46cmTROUGH" WhatMoreWebCategory="Garden Products" />
</Rows>

此代码输出属于该 WhatMoreProductSubRange 的所有产品,但我不想在我的产品列表中重复产品(在 A 部分中提到)(在 B 部分中提到)。我不知道如何避免重复,因为我是新手到 xml 解析。请帮助我。

4

1 回答 1

0

排序。虽然效率较低,但这个工作正常。

<?
$list = groupBy(file_get_contents('XML/output.xml'), "WhatMoreProductSubRange");
$id=urldecode($this->uri->segment(4));
$id2=$this->uri->segment(3);
foreach ($list[$id] as $product) 
{
if ($id2==$product->Code)
{
$subcat=$product->WhatMoreProductSubRange;
 ?>
 <h1><?=$product->Name?></h1>
 <?
}
}     
?>
<?
 $list = groupBy(file_get_contents('XML/output.xml'), "WhatMoreProductSubRange");
 $id=urldecode($this->uri->segment(4));
 $id2=$this->uri->segment(3);
 foreach ($list[$id] as $product ) 
 {
   if ($id2!=$product->Code)
   {
    $subcat2=$product->WhatMoreProductSubRange;
 ?>
      <h2><?=$product->Name?></h2>
 <?
   }
  } 
  ?>
于 2012-11-02T09:51:58.113 回答