PHP处理多维数组值 [英] PHP manipulating multidimensional array values
问题描述
我有一个结果集,它是来自数据库的数组,如下所示:
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"
)
)
我如何应用函数将仅在数组键上的数组值替换为b?通常,我只会使用foreach循环重建一个新数组,并在数组键为b的情况下应用该函数,但是我不确定这是否是最佳方法.我尝试看过许多数组函数,似乎array_walk_recursive是我可以使用的东西,但是我没有运气让它完成我想要的事情.如果我对它的描述不够好,基本上我希望能够像下面的代码那样做:
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?
推荐答案
使用 array_walk_recursive
:
如果您的PHP> = 5.3.0(用于匿名函数):
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!';
}
});
否则类似:
function _my_method(&$item, $key) {
if ($key == 'b') {
$item = 'the key is b!';
}
}
array_walk_recursive($result, '_my_method');
这篇关于PHP处理多维数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!