0

I'm trying to build a tree-map from categories. I have the categories (I have a lot of categories and I want to remove duplicates and show them in a tree-map view with count) and I have the following code:

<?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);

OUTPUT:

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

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

        )

)

I would like to be:

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

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

        )

)

1 Answers1

0

You're losing information with both of those formats and the suggested answer is not going to cut it. You do need recursion and each item needs to hold a count and children.

$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);
Walf
  • 8,535
  • 2
  • 44
  • 59