hamza
4 months ago

Get Full Key from Multidimensional Array

Posted 4 months ago by hamza

Let's say I have this array:

[
    'a' => [
        'b' => [
            'c' => 1,
            'd' => 2,
        ],
        'e' => [
            'f' => 3,
            'g' => 4
        ],
        'h' => [
            'i' => [
                'j' => 5
            ],
        ],
        'j' => [
            'k' => 2
        ]
    ]
];

What I want is a PHP function that accepts this array as well as a key. Let's say the key is 'j'. Then it should return an array that contains the full key to access all 'j' keys in the array.

For this array, it should return

[
    'a.j',
    'a.h.i.j'
];

In this way, I will be able to access the values of the array using this full key and edit its value. But I want to search using a single key that could be anywhere in the array.

I know it will be done using the recursive technique but I could not do it.

Any help will be appreciated. Thanks.

Please sign in or create an account to participate in this conversation.