我正在尝试使用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:output.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解析的新手。请帮助我。
答案 0 :(得分: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>
<?
}
}
?>