0

Rewriting this to be more specific.

I have a csv file. Every row has has a field that explodes into an array of representing a category tree. So, the first three rows might become arrays as such:

array('food', 'fruit', 'red', 'apple')
array('food', 'fruit', 'green', 'kiwi')
array('beauty', 'makeup', 'lipstick')

It is supposed to be a tree, though. I need to end up with:

food
    fruit
        red
            apple
        green
            kiwi
beauty
    makeup
        lipstick

The main difference from this and the dozens of similar questions I've seen asked and answered is that there is no guaranteed number of levels in each record read, and the distinct likelihood that one record may have no keys in common with another. So array_merge seems to fail as does using +

The only assurance is that for any record, the list of keys is assumed to begin at the top level of the array, so that if there is

rec1 = animal, fish, shark
rec2 = fish, shark, hammerhead

the expected result is

animal
    fish
        shark
fish
    shark
        hammerhead

2 Answers 2

2
$i = count($array) - 1;
$new_array = $array[ $i ];

while ( $i-- ) {
    $new_array = array( $array[ $i ] => $new_array );
}

See it here in action: http://codepad.viper-7.com/bVWYrN

Sign up to request clarification or add additional context in comments.

3 Comments

So for that one record, this looks to work. But what if the next record read is ('food', 'fruit', 'green', 'kiwi') ... so two indexes already exist?
@Ayen - Is the depth guaranteed? Meaning, will all the arrays have four items?
No. It is a feed of products, so there can be: beauty -> skin cream or beauty -> makeup -> lipstick -> gloss
0

Here's a possible solution, using recursion.

<?php
$foo = array('food', 'fruit', 'red', 'apple');

function categorize($arr) {
        if (count($arr) > 2) {
                $temp[$arr[0]] = categorize(array_slice($arr, 1));
        } else {
                $temp[$arr[0]] = array($arr[1]);
        }   
        return $temp;

}
print_r(categorize($foo));

Output:

Array
(
    [food] => Array
        (
            [fruit] => Array
                (
                    [red] => Array
                        (
                            [0] => apple
                        )

                )

        )

)

Link with further examples: http://codepad.org/xmK1oYy1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.