dongqiaogouk86049 2015-07-15 14:08
浏览 70
已采纳

在没有很多循环的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 like foreach($dropdown->children()->children() ...)

I know there are a few semi-similar questions on SO but they're slightly different and the answers are mediocre.

  • 写回答

3条回答 默认 最新

  • douyao3895 2015-07-15 14:11
    关注

    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
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办