在没有很多循环的PHP中访问嵌套数组
Consider the following:
$dropdown = array (
"unitofmeasure" => array (
"m" => "meters",
"ft" => "feet"
),
"facing_direction" => array (
"0" => array ("West","North-West","North","North-East","East","South-East"),
"1" => array("South","South-West")
)
....
)
Assume there are n number of sub arrays, not just the two shown above.
Iteration solution:
foreach($dropdown as $key => $val) {
foreach($val as $k => $v) {
foreach($v as $id => $value) {
//manipulate values here
}
}
}
My question is:
is there not a more elegant solution available in PHP?
for example something likeforeach($dropdown->children()->children() ...)
I know there are a few semi-similar questions on SO but they're slightly different and the answers are mediocre.
请考虑以下事项: p>
$ dropdown = array(\ n“unitofmeasure”=>数组(
“m”=>“米”,
“ft”=>“脚”
),
“facing_direction”=>数组(
“0 “=>数组(”西“,”西北“,”北“,”东北“,”东“,”东南“),
”1“=>数组(”南“) ,“西南”)
)
....
)
code> pre>
假设有 n em>个子数 数组,不仅仅是上面显示的两个。 p>
迭代解决方案: p>
foreach($ dropdown as $ key => $ val){
foreach($ val as $ k => $ v){
foreach($ v as $ id => $ value){
//在此操纵值
}
}
}
code> pre>
我的问题是: p>
PHP中没有更优雅的解决方案吗? strong>
例如 foreach($ dropdown-> children() - > children()...) code> p>
blockquote>
我知道在SO上有一些半相似的问题,但它们略有不同,答案是平庸的。 sub> p>
div>
Yes, I personally tend to use array_walk_recursive
with a closure(if you're using PHP above 5.3).
You can, obviously, also use recursion if you like getting your hands dirty.
I suppose an example is in order:
$array = [ 0 => [0 => [ 0 => 1 ...]]];
$manipulated_array = [];
array_walk_recursive($array, function($value) use (&$manipulated_array)
{
// do whatever you wish here
});
foreach() just expects an array, so if you only need to iterate ONE of those deeply nested arrays, then you can quite easily have
foreach($arr['level1']['level2'][...]['levelGazillion'] as ...)
I tend to use recursion in these situations:
function modify_array(&$arr)
{
if (is_array(arr)) {
foreach($arr as &$val) {
modify_array($val);
}
} else {
modify_value($arr);
}
}
where modify_value(&$val)
is whatever you want to do to each non-array child at any arbitrary depth