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 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数