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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?