Mike Silvis
Mike Silvis

Reputation: 1309

Create an hierarchical from an array of arrays

I have the following

Array
(
    [1298650982] => Array
        (
            [genre] => Action
            [date] => 90s
            [rate] =>; 4
            [title] => Braveheart
        )

    [1298651271] => Array
        (
            [genre] => Action
            [date] => 90s
            [rate] => 3
            [title] => Top Gun
        )

)

and am trying to build a hierarchical system where it would return something like this

basically combine the arrays where they have similar values. Thanks, Mike

Upvotes: 1

Views: 290

Answers (1)

Blair McMillan
Blair McMillan

Reputation: 5349

Loop through your array and build a new array for your values. Something like:

$result = array();
foreach ($array as $key => $item) {
    $result[$item['genre']][$item['date']][$key] = array(
        'title' => $item['title'],
        'rate' => $item['rate']
    );
}

Would give you:

Array
(
    [Action] => Array
        (
            [90s] => Array
                (
                    [1298650982] => Array
                        (
                            [title] => Braveheart
                            [rate] => 4
                        )

                    [1298651271] => Array
                        (
                            [title] => Top Gun
                            [rate] => 3
                        )

                )

        )

)

A little hard to tell from your question as to whether that was the type of formatting that you wanted. But you should be able to adjust it from here to get it to what you want.

Upvotes: 3

Related Questions