PHP managing multidimensional array values
I have a result set as an array from a database that looks like this:
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 to apply a function to replace array values only with an array key using b? Normally, I would just rebuild the new array with the foreach loop and apply the function if the array key is b, but I'm not sure if this is the best way. I tried to take a look at the many functions of the array, and it seemed that array_walk_recursive is what I can use, but I was not lucky that it did what I want. If I will not describe it well enough, basically I want to be able to do as the following code 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 this, or is there a better way?
use array_walk_recursive described here
$replacer = function($x) {return "I used to be called $x";}; //put what you need here
$replaceB = function(&$v, $k) use ($replacer) {if ($k === 'b') $v = $replacer($v);};
array_walk_recursive($arr, $replaceB);
Function replacermay be redundant. You can replace it with a literal or whatever you like.