1

I have an array I'm trying to change this arrays's some keys but function fails for arrays which are recursive.

What could be problem

Any one can fix this?

$array = array(
    array(
        'tag' => 'div',
        'class' => 'lines',
        array(
            'tag' => 'div',
            'repeat' => array(
                'tag' => 'div',
                 array(
                    'tag' => 'span',
                    'style' => 'margin:10px; padding:10px',
                    'key' => 'title',
                ),
                'key' => 'subject',
            )
        )
    )
);



function update_recursively($array, $key = '', $value = array()) {
    //print_r($array); print_r($value);
    foreach ($array as $k => $v) {
        if ($k === $key){ 
            $array[$k] = $value;
        }
        elseif (is_array($v))
            $array[$k] = update_recursively($v);
    }
    return $array;
}

print_r(update_recursively($array, 'repeat', array('d' => 'a')));

1 Answer 1

1

You forget to pass 2nd and 3rd parameter to inner function call:

function update_recursively($array, $key = '', $value = array()) {
    //print_r($array); print_r($value);
    foreach ($array as $k => $v) {
        if ($k === $key){ 
            $array[$k] = $value;
        } elseif (is_array($v)) {
            $array[$k] = update_recursively($v, $key, $value);    // Here
        }
    }
    return $array;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much u_mulder I think I been tired.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.