assign value to last multidimensional array

时间:2018-02-03 09:49:05

标签: php

i just want to assign array value to my last array inside multidimensional array. Here is my array

Array (
[college] => Array (
    [student] => Array (
        [contact] => Array ()
    )
    [parents] => Array (
         [contact] => Array ()
    ) 
) 
[school] => Array (
    [parents] => Array (
        [contact] => Array ()
    )
    [student] => Array (
         [contact] => Array ()
    ) 
    [data] => Array (
         [contact] => Array()
    )
))

Things are that every things is dynamic some time it could be simple array or might be multidimensional array. every key and value are dynamic i want to assign array value to last array eg. i want something like that.

$assignArray = array('primary_number'=>123,'main_number'=>123);
Array (
[college] => Array (
    [student] => Array (
        [contact] => Array ('primary_number'=>123,'main_number'=>123)
    )
    [parents] => Array (
         [contact] => Array ('primary_number'=>123,'main_number'=>123)
    ) 
) 
[school] => Array (
    [parents] => Array (
        [contact] => Array ('primary_number'=>123,'main_number'=>123)
    )
    [student] => Array (
         [contact] => Array ('primary_number'=>123,'main_number'=>123)
    ) 
    [data] => Array (
         [contact] => Array('primary_number'=>123,'main_number'=>123)
    )
))

can any one solve it? any help will appreciate..

1 个答案:

答案 0 :(得分:1)

Use a recursive procedure:

function replace_leaf_arrays(&$array, $replacement) {
    foreach ($array as &$val) {
        if (empty($val)) {
            $val = $replacement;
        } else {
            replace_leaf_arrays($val, $replacement);
        }
    }
}

replace_leaf_arrays($main_array, $assignArray);