Dev Frnds
Dev Frnds

Reputation: 19

How can I make breadcrumbs from a array?

This is the sample array

Array
    (
        [note] => Array
            (
                [to] => Array
                    (
                        [user] => Array
                            (
                                [name] => First User
                            )
    
                        [abc] => 123
                        [lmn] => 4582
                    )
    
                [from] => Jani
                [heading] => Reminder
                [body] => Array
                    (
                        [abc] => 123
                    )
    
            )
    
    )

I want the following output from the above array.

note > to > user > name

note > to > abc

note > to > lmn

note > from

note > heading

note > body > abc

Upvotes: 0

Views: 656

Answers (1)

Benoit Esnard
Benoit Esnard

Reputation: 2075

An easy way to do it is via a recursive function:

function breadcrumb($array) {
    $output = [];

    foreach ($array as $key => $value) {
        if (is_array($value)) {
            foreach (breadcrumb($value) as $breadcrumb) {
                $output[] = $key . ' > ' . $breadcrumb;
            }
        } else {
            $output[] = $key;
        }
    }
    return $output;
}

Try it online.

Upvotes: 1

Related Questions