PHP - Recursively insert a key/value pair after a specific key in multidimensional array - Hack The Tech - Latest News related to Computer and Technology

Hack The Tech - Latest News related to Computer and Technology

Get Daily Latest News related to Computer and Technology and hack the world.

Friday, November 19, 2021

PHP - Recursively insert a key/value pair after a specific key in multidimensional array

I have an indexed array containing any number of nested associative or indexed arrays. I need to recursively insert a new key/value pair 'apple' inside each contained array if the array contains a key 'banana' while keeping all other data intact and either modify the original array or create a new array.

$original = [
    0 => [
        'something1' => 'something',
        'banana' => 'yellow',
        'something2' => [
            'something3' => 'something',
            'something4' => [
                'something5' => 'something',
                'banana' => 'yellow',
                'something6' => [
                    'banana' => 'yellow',
                ]
            ],
            'banana' => 'yellow',
        ],
        'something7' => [
            0 => [
                'something8' => 'something',
                'banana' => 'yellow',
            ],
        ],
    ],
    1 => [
        'something9' => 'something',
        'banana' => 'yellow',
    ],
];

This is the expected result - 'apple' doesn't have to be inserted immediately next to 'banana', it can be located anywhere in the same level array as long as it's a sibling of 'banana'.

$new = [
    0 => [
        'something1' => 'something',
        'banana' => 'yellow',
        'apple' => 'red',
        'something2' => [
            'something3' => 'something',
            'something4' => [
                'something5' => 'something',
                'banana' => 'yellow',
                'apple' => 'red',
                'something6' => [
                    'banana' => 'yellow',
                    'apple' => 'red',
                ]
            ],
            'banana' => 'yellow',
            'apple' => 'red',
        ],
        'something7' => [
            0 => [
                'something8' => 'something',
                'banana' => 'yellow',
                'apple' => 'red',
            ],
        ],
    ],
    1 => [
        'something9' => 'something',
        'banana' => 'yellow',
        'apple' => 'red',
    ],
];

I could find answers on how to insert key/value pair after certain key in a flat array, but not an answer for doing so recursively in a multidimensional array.



source https://stackoverflow.com/questions/70023516/php-recursively-insert-a-key-value-pair-after-a-specific-key-in-multidimension

No comments:

Post a Comment