S
S
siricks2016-12-04 13:01:52
PHP
siricks, 2016-12-04 13:01:52

Adding data to multidimensional array to any depth?

There is an array of unlimited nesting, for example:

$storage = [
    'people' => ['Name' => 'Bill' , 'Surname' => 'Milligan', 'age' => '32', 'sex' => 'male',
                'children' => ['name' => 'Sara', 'surname' => 'Milligan', 'age' => '10', 'sex' => 'female', 'mother' => 'Megan Milligan',
                'schools' => ['first' => ['name' => 'Priston School', 'address' => 'USA']]]
    ]
];

We need to make a function that can add data inside the array to any depth:
function set($param, $data){
    
}

where $param is the add address like 'people\children\schools\second' , and $data is the data to add, for example: '['name' => 'Second School', 'address' => 'USA']' .
As a result, in fact, the operation should be performed
$storage['people']['children']['schools']['second'] = ['name' => 'Second School', 'address' => 'USA'];

The catch is how to ensure that data is added to the array to any depth

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Snewer, 2016-12-04
@Snewer

function set_array_value(&$array, $key, $value){
        if(!is_array($key)){
            $key = explode('\\', $key);
        }

        $currentKey = array_shift($key);
        
        if(!is_array($array[$currentKey])){
            if(!isset($array[$currentKey])){
                $array[$currentKey] = [];
            } else {
                $array[$currentKey] = [ $array[$currentKey]];
            }
        }

        if(count($key) > 0){
            set_array_value($array[$currentKey], $key, $value);
        } else {
            if(is_array($array[$currentKey])){
                $array[$currentKey][] =  $value;
            } else {
                $array[$currentKey] = [$array[$currentKey], $value];
            }
        }
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question