dthok9648 2019-01-25 21:14
浏览 188
已采纳

难以从阵列的foreach中删除数组中的记录

So I have an multidementional array, $lines, that was generated from a csv file. Its populated with records that look like the following:

 [0] => 038572 
 [1] => L 
 [2] => Testing
 [3] => BQ
 [4] => 
 [5] => 52.40308886
 [6] => -0.19266809
 [7] => 01/12/2018
 [8] => 
 [9] => B
 [10] => 
 [11] => 5
 [12] => 
 [13] => 
 [14] => 
 [15] => 
 [16] => ldn d 5BQ
 [17] => 038572
 [18] =>

I also have records which are all empty accept for one bit which has:

[16] => ,

Its these records that I'm trying to unset. So I tried the following:

foreach($lines as $element) {
    if ($element[16] == ",") {
        unset($element);
    }
}

But when I print_r the array $lines, I can still see those partially empty records.

  • 写回答

3条回答 默认 最新

  • du521521521 2019-01-25 21:17
    关注

    You're working on a temporary copy inside your loop, so when you unset $element, it has no effect on the original $lines array. You can use references, or unset the value from the original array:

    foreach ($lines as $index => $element) {
        if ($element[16] === ',') {
            unset($lines[$index][16]);
        }
    }
    

    Or something like this:

    for ($i = 0, $_i < count($lines); $i < $_i; $i++) {
        if ($lines[$i][16] === ',') {
            unset($lines[$i][16]);
        }
    }
    

    Or any of a dozen other ways to do the same...

    Note, using unset() here will actually remove the item from the array, which may misalign your columns depending on how you have your code written. Instead of unsetting it, you may want to set it to null.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置