dongni3854 2015-08-17 14:17
浏览 65
已采纳

在PHP中处理多维csv发起的数组

Within the first column of every row lies a position, i.e. Software Engineer, and if the user's position matches the one in that row, the nested for loop should check in each column of that row if the given id exists in the csv string for that column. I haven't worked much with arrays in PHP and most of my experience with multidimensional arrays lies within Java so pardon my java-themed PHP code:

$csv = read_csv('/filepath/tct.csv');
$csv_rows = 75;
for($i=1;$i<$csv_rows;$i++)
{
    if(strtolower($user['user_pos']) == strtolower($csv[$i][0]))
    {
        for($j=1;j<sizeof($csv[$i]);j++)
        {
            if(array_search($user['id'], explode(",",$csv[$i][$j])))
            {
                return true;
            }
        }
    }
}

Unfortunately, my java doesn't seem to work and all of the existing questions concerning PHP multidimensional arrays only confuse me with the $key->$value talk. Can anyone explain to me what I need to do adjust to get this to work?

  • 写回答

1条回答 默认 最新

  • doubi4340 2015-08-17 19:16
    关注

    So what I was doing is a perfectly acceptable (in terms of functionality) when processing multidimensional arrays, I just neglected to place the $ before j twice in the inner loop.

    The most efficient and understandable way I've found thus far is:

    foreach($csv as $csv_row) {
        for($i=1;$i<count($csv_row);$i++) {
            //do something with $csv_row[$i]
        }
    }
    

    The standard-issue nested for loop is to ensure the row names aren't iterated over since I always had row names at column[0] (despite the fact that the outer foreach will loop over the column names in row 0)

    Of course, this is heavily reliant on someone using the same spreadsheet/csv layout. If it's a csv of just data, I'm sure the inner loop could be changed to:

    foreach($csv_row as $csv_col {
        //do something with $csv_col
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?