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?
Looping through multidimensional arrays Just as with regular, single-dimensional arrays, you can use foreach to loop through multidimensional arrays. To do this, you need to create nested foreach loops — that is, one loop inside another: The outer loop reads each element in the top-level array.
It can be created using nested array. These type of arrays can be used to store any type of elements, but the index is always a number. By default, the index starts with zero. print_r( $myarray );
A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.
What is nested array in PHP? In the above example Create a variable $arr with value an nested array. Here at the place of array's first element there is also an array with three value like $arr[0][0]=10, $arr[0][1]=10, and $arr[0][2]=10.
Using array_walk_recursive
:
If you have PHP >= 5.3.0 (for anonymous functions):
array_walk_recursive($result, function (&$item, $key) {
if ($key == 'b') {
$item = 'the key is b!';
}
});
Otherwise something like:
function _my_method(&$item, $key) {
if ($key == 'b') {
$item = 'the key is b!';
}
}
array_walk_recursive($result, '_my_method');
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