php 从XML导入产品类别

mcdcgff0  于 2023-02-18  发布在  PHP
关注(0)|答案(1)|浏览(79)

当我拉取类别时,我不希望列出相同的类别,但它列出了所有类别。如果您能帮助我,我将非常高兴。谢谢。XML文件

<?xml version="1.0" encoding="UTF-8"?>
-<products>
-<product>
<product_code>AXX-655</product_code>
<product_name>Samsung Led TV</product_name>
<categories>Electronic > Home Electronic > TV</categories>
</product>
-<product>
<product_code>ACC-124</product_code>
<product_name>Fleece Coat</product_name>
<categories>Clothes > Man Clothes > Coat</categories>
</product>
-<product>
<product_code>ADF-147</product_code>
<product_name>LG 2103 Led TV</product_name>
<categories>Electronic > Home Electronic > TV</categories>
</product>
-<product>
<product_code>AXX-655</product_code>
<product_name>Sony Led TV</product_name>
<categories>Electronic > Home Electronic > TV</categories>
</product>
-</products>

PHP文件

<?php
$xml = simplexml_load_file('xml/localxmlfile3.xml') or die("Error: Cannot create object");
foreach ($xml->children() as $child) {  
     $categories = trim($child->categories);
   echo  $categories."<br>";
}

产出

Electronic > Home Electronic > TV
Clothes > Man Clothes > Coat
Electronic > Home Electronic > TV
Electronic > Home Electronic > TV

"我想要"

Electronic > Home Electronic > TV
Clothes > Man Clothes > Coat

我打算分别得到类别和子类别。但是它重复的数量和产品的数量一样多。我尝试使用array_unique函数,但它不起作用。

hgc7kmma

hgc7kmma1#

你需要创建一个helper数组来检查类别是否存在(in_array($val, $array_name) //return true or false

<?php 
$xml = simplexml_load_file('xml/localxmlfile3.xml') or die("Error: Cannot create object");
$category_helper = array();
foreach ($xml->children() as $child) {  
    $category_name = trim($child->categories);
    //if not exist in our helper array we add this
    if(!in_array($category_name, $category_helper)) {
        $category_helper[] = $category_name;
    }
} 
var_dump($category_helper);
?>

相关问题