I have a result set as an array from a database that looks like:
array (
0 => array (
"a" => "something"
"b" => "something"
"c" => "something"
)
1 => array (
"a" => "something"
"b" => "something"
"c" => "something"
)
2 => array (
"a" => "something"
"b" => "something"
"c" => "something"
)
)
How would I apply a function to replace the values of an array only on the array key with b? Normally I would just rebuild a new array with a foreach loop and apply the function if the array key is b, but I'm not sure if it's the best way. I've tried taking a look at many array functions and it seemed like array_walk_recursive is something I might use, but I didn't have luck in getting it to do what I want. If I'm not describing it well enough, basically I want to be able to do as the code below does:
$arr = array();
foreach ($result as $key => $value)
{
foreach ($value as $key2 => $value2)
{
$arr[$key][$key2] = ($key2 == 'b' ? $this->_my_method($value2) : $value2);
}
}
Should I stick with that, or is there a better way?
Using
array_walk_recursive
:If you have PHP >= 5.3.0 (for anonymous functions):
Otherwise something like:
Untested but I think this will work.
The function will move through an array checking the keys for
b
. If the key points to an array it recursively follows it down.use
array_walk_recursive
documented hereThe
replacer
function might be overkill. You can replace it with a literal or anything you like.