doubi12138 2016-08-28 00:23
浏览 58
已采纳

试图在PHP中将CSV行作为二维数组

So I'm trying to read a CSV which has a couple of lines and will be compared with a User-Input. This input is an array of id's the user chooses ($talente). The array with the id's will be splitted, the script opens the CSV and reads the line equal to the id's. It works nice but reads the CSV line by line into another one-dimensional array. But I need the lines to be an array already, so that I get a two-dimensional array at the end.

My script so far looks like this:

<?php

$talente = $_GET['talente'];

$talentline = array();

$i = 0;
$myFile = fopen("talente.csv", "r");

foreach ($talente as $talent) {
    if ($talent == $i+1) {          
        while (($data = fgetcsv($myFile, 1000, ",")) !== FALSE) {

            $num = count($data);

                for ($c=0; $c < $num; $c++) {
                    $talentline[][] = $data[$c];
                }

        //$talentline[] = $lines[$i];

        }
        fclose($myFile);
    }
    $i++;

}

print_r(array_values($talentline));

/*echo $talentline[1];
echo $talentline[2];
*/
?>

The outcome so far is every line with every element, but in a one-dimensional array instead of a two-dimensional:

Array ( [0] => Array ( [0] => Schild ) [1] => Array ( [0] => 1 ) [2] => Array ( [0] => Licht ) [3] => Array ( [0] => 1w10 ) [4] => Array ( [0] => - ) [5] => Array ( [0] => Schutz ) [6] => Array ( [0] => 1 ) [7] => Array ( [0] => Licht ) [8] => Array ( [0] => 1w10 ) [9] => Array ( [0] => - ) [10] => Array ( [0] => Licht ) [11] => Array ( [0] => 4 ) [12] => Array ( [0] => Licht ) [13] => Array ( [0] => 1w10 ) [14] => Array ( [0] => - ) [15] => Array ( [0] => Genesung ) [16] => Array ( [0] => 1 ) [17] => Array ( [0] => Licht ) [18] => Array ( [0] => - ) [19] => Array ( [0] => - ) [20] => Array ( [0] => Aufopfern ) [21] => Array ( [0] => 1 ) [22] => Array ( [0] => Licht ) [23] => Array ( [0] => - ) [24] => Array ( [0] => - ) ) 
  • 写回答

1条回答 默认 最新

  • dqb77047 2016-08-28 09:21
    关注

    What about this? Read the CSV once for speed, then use array_filter and in_array to filter the CSV down to the desired rows.

    <?php
    
    $talente = $_GET['talente'];
    
    $myFile = fopen("talente.csv", "r");
    $csv = [];
    while ($data = fgetcsv($myFile, 1000, ",")) {
        $csv[] = $data;
    }
    fclose($myFile);
    
    $talentLine = array_filter($csv, function($key) use ($talente) {
        return in_array($key, $talente);
    }, ARRAY_FILTER_USE_KEY);
    
    print_r(array_values($talentline));
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题