Viktors
Viktors

Reputation: 935

Transform tree category array to one line

I have got an array (category tree)

[category_name_en] => en
[category_name_ru] => ru
[id_category] => 86314
[children] => Array
    (
        [category_name_en] => en 2
        [category_name_ru] => ru 2
        [id_category] => 86296
    )

this I got from database - recursion

I'm trying to get such output

[category_en] => en > en2;
[category_ru] => ru > ru2;

In thise example array have two levels but it can be more levels... please give me an idea or help.

Upvotes: 0

Views: 81

Answers (1)

deceze
deceze

Reputation: 522109

Something simple like this to get you started:

function flattenChildren(array $array, $key) {
    $chain = !empty($array['children']) ? flattenChildren($array['children'], $key) : array();
    array_unshift($chain, $array[$key]);
    return $chain;
}

foreach ($categories as $category) {
    echo join(' > ', flattenChildren($category, 'category_name_en')), "\n";
}

Upvotes: 1

Related Questions