saqueib
10 months ago
107
1
General

Clean way to update nested array field value

Posted 10 months ago by saqueib

Hey folks, I wanted to ask do you know any clean way to do the update on nested values inside an array. I have done it using foreach loop 3 level of it ?.

Maybe you guys can suggest something cleaner

$config = [
    'sections' => [
        'sun' => [
            'options' => [
                [
                    'id' => 3,
                    'name' => 'Option 1',
                    'value' => 2,
                ],
                [
                    'id' => 4,
                    'name' => 'Option 2',
                    'value' => 4,
                ]
            ]
        ],
        'mon' => [
            'options' => [
                [
                    'id' => 1,
                    'name' => 'Option 5',
                    'value' => 5,
                ]
            ]
        ],
    ]
];

dd(updateValues($config));

function updateValues(array $config)
{
    // update the sections.sun.options value
    foreach (array_get($config, 'sections') as $sectionKey => $section) {
        foreach (array_get($section, 'options', []) as $index => $input) {
            foreach ($input as $key => $value) {
                if (in_array($key, ['value', 'name'])) {
                    array_set($config, 'sections.' . $sectionKey . '.options.' . $index . '.' . $key, $value. " updated");
                }
            }
        }
    }

    return $config;
}

I want to update the options.value which will be path like this array_set($config, "sections.sun.options.0.value", " updated");

You can use a laravel collection if needed. ?

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