Multi-level categories - single array to multidimensional array

Viewed 108

I'm trying to get my head around solving the following:

I have a string that has this pattern:

Category 1 > SubCategory 2 > SubSubCategory 3 > SubSubSubCategory 4 ... etc.

I am using the explode function by '>' to convert the string into an array. Now my final output should be something like this:

$categories[ 'Category 1' ][ 'SubCategory 2' ][ 'SubSubCategory 3' ][ 'SubSubSubCategory 4'][...etc...]

I assume I should be using a recursive function but I simply can't get my head around it. The solution should cater for an unlimited number of subcategories.

Any ideas?

2 Answers

Well I have a solution that maybe is not the most efficient but that can help you solve what you need, and maybe it's easier for you to understand.

<?php
$categories = "Category 1 > SubCategory 2 > SubSubCategory 3 > SubSubSubCategory 4";

$splited = explode(">", $categories);

$reversed = array_reverse($splited);

$result = array();

foreach($reversed as $category) {
    $result = [trim($category) => $result];
}

var_dump($result);

Basically I did the same as you, I used an explode() to separate each category. In the next line I reversed this array, so I can add the categories from the last to the first level. In foreach with this array reversed, every loop I add the previous array as value and pass the currently category name as key into the same variable. This makes each created array be associative to the previous one.

It's the first time I've been helping someone on the platform so I'm sorry my English is a little bit wrong.

First, let's do an explode that gets rid of whitespaces as well:

$categories = explode(" > ", "Category 1 > SubCategory 2 > SubSubCategory 3 > SubSubSubCategory 4");

Now, let's build our nested array:

$categories = explode(" > ", "Category 1 > SubCategory 2 > SubSubCategory 3 > SubSubSubCategory 4");
$nested = "somevalue"; // The answer did not specify what the ultimate value should be.
for ($index = count($categories); $index >= 0; $index--) {
    $nested = [$nested];
}
//$nested is the array that you wanted to build.

Since the code above does not assume a maximum level, you can go on and on and on with the subcategories.

Related