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 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了