Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace certain items within multidimensional array

I have an array that can vary in how many arrays deep there are, for example:

        array(
              'one' => array(
                             array(
                                'something' => 'value'
                                ),
                             array(
                                'something2' => 'value2'
                                ),
                             'another' => 'anothervalue'
                             ),
              'two' =>  array(
                             array(
                                'something' => 'value'
                                ),
                             array(
                                'something2' => 'value2'
                                ),
                             'another' => 'anothervalue'
                             )
              )

Now, let's say I want to replace everything with the key 'something'.

Would I need to use a recursive function to iterate through the array? or is there a better way?

Thank you!

like image 893
dzm Avatar asked Dec 17 '22 08:12

dzm


2 Answers

Have a look at array_walk_recursive. It may be quite handy in a situation like this.

Here's an example using array_walk_recursive:

$arr = array(
      'one' => array(
            array('something' => 'value'),
            array('something2' => 'value2'),
            'another' => 'anothervalue'
            ),
      'two' =>  array(
            array('something' => 'value'),
            array('something2' => 'value2'),
            'another' => 'anothervalue'
            )
       );

function update_something(&$item, $key)
{
    if($key == 'something')
        $item = 'newValue';
}

array_walk_recursive($arr, 'update_something');

If used inside a class the callback method have to add the object along with the function. This is achieved with an array:

array_walk_recursive($arr, array($this, 'update_something'));
like image 121
Marcus Avatar answered Jan 03 '23 04:01

Marcus


This is a function that you can either be used as a global function or you just put it into a class:

/**
 * replace any value in $array specified by $key with $value
 *
 * @return array array with replaced values
 */
function replace_recursive(Array $array, $key, $value)
{
    array_walk_recursive($array, function(&$v, $k) use ($key, $value)
        {$k == $key && $v = $value;});
    return $array;
}

# usage:
$array = replace_recursive($array, 'something', 'replaced');

It's also making use of array_walk_recursive but encapsulated. The key and the value can be specified as function parameters and not hardencoded in some callback, so it's more flexible.

like image 39
hakre Avatar answered Jan 03 '23 05:01

hakre