计算树形图中的重复项

时间:2016-12-05 22:30:29

标签: php

我正在尝试从类别构建树形图。我有类别(我有很多类别,我想删除重复项并在带有计数的树形图视图中显示它们),我有以下代码:

<?php
$cat = array(
    "Sneakers/Men",
    "Sneakers/Women",
    "Accessories/Jewellery/Men",
    "Accessories/Jewellery/Men",
    "Accessories/Jewellery/Women",
    "Accessories/Jewellery/Men/Bvlgari"
);

$out = [];
foreach ($cat as $str) {
    $lookup = &$out;
    $parts = explode("/", $str);
    foreach ($parts as $part) {
        $lookup = &$lookup[$part];

        if (!isset($lookup))
            $lookup = [];
        if ($part == end($parts))
            $lookup = is_array($lookup) ? 1 : ++$lookup;
    }
}

print_r($out);

输出:

Array
(
    [Sneakers] => Array
        (
            [Men] => 1
            [Women] => 1
        )

    [Accessories] => Array
        (
            [Jewellery] => Array
                (
                    [Men] => 3
                    [Women] => 1
                )

        )

)

我想成为:

Array
(
    [Sneakers] => Array
        (
            [Men] => 1
            [Women] => 1
        )

    [Accessories] => Array
        (
            [Jewellery] => Array
                (
                    [Men] => Array (
                        [Bvlgari] => 1
                    )
                    [Women] => 1
                )

        )

)

1 个答案:

答案 0 :(得分:0)

您使用这两种格式丢失信息,建议的答案不会削减它。你需要递归,每个项目需要持有一个计数和孩子。

$cat_paths = [
    'Sneakers/Men',
    ...
];
$cat_counts = $item = [# template of each item
    'count' => 0,
    'children' => [],
];
foreach ($cat_paths as $cat_path) {
    $level = &$cat_counts;# use a reference for recursion
    if ($cat_path) {# allow uncategorized to be in root of tree
        $cat_path = explode('/', $cat_path);
        do {
            $cat = array_shift($cat_path);
            if (!isset($level['children'][$cat])) {
                $level['children'][$cat] = $item;
            }
            $level = &$level['children'][$cat];# step down into tree
        } while ($cat_path);
    }
    $level['count']++;
}
unset($level);