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!
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'));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With