dongwei8440 2012-11-18 02:32 采纳率: 100%
浏览 31
已采纳

通过嵌套的foreaches在多维数组中取消设置键

Seems strange I can't find an answer to this, but here goes:

This:

foreach ($stuffs as $stuffRow) {
    foreach ($stuffRow as $stuff) {
        if($stuff=== null){
            unset($stuff);
        }
    }
}

is not working.

I know I shouldn't say "isn't working", but that's all I've got. The if condition works; I've tested it. However, when I apply unset, the key=>value is still there.

Note: PHP 5.3

Many thanks in advance!

  • 写回答

1条回答 默认 最新

  • dongtidai6519 2012-11-18 02:42
    关注

    While this might work (i never do it this way and not tested it):

    foreach ($stuffs as &$stuffRow) {
        foreach ($stuffRow as &$stuff) {
            if($stuff=== null){
                unset($stuff);
            }
        }
    }
    

    If i remember correctly, passing by reference isn't a good idea in foreachs (but can't remember why, might have been in the php doc somewhere, maybe someone can clarify in the comments, but i think it's because foreach works on a copy of the array and passing a reference passes the reference to the copy, not the original, though that is just an educated guess). Instead, try this.

    foreach ($stuffs as $key1=>$stuffRow) {
        foreach ($stuffRow as $key2=>$stuff) {
            if($stuff=== null){
                unset($stuffs[$key1][key2]);
            }
        }
    }
    

    The reason your code didn't work by the way is because foreach loops iterate over a COPY of your array.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学中在线排序的时间在线排序的在线LPT算法
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试,帮帮忙吧