0

我正在尝试使用 PHP 从 csv 中仅选择某些列。目前我正在使用:

$theData = array(
    array( 'col1', 'col2', 'col3', 'col4', 'col5' ),
    array( 'col1', 'col2', 'col3', 'col4', 'col5' ),
    array( 'col1', 'col2', 'col3', 'col4', 'col5' )
    );
$picked = '1, 3, 5';

$totalColumns = count( $theData[0] );
$columns = explode( ',', $picked );
foreach( $theData as $k => &$thisData ) {
    for( $x = 1; $x < $totalColumns + 1; $x++ ) {
        if( ! in_array( $x, $columns ) ) {
            unset( $thisData[$x - 1] );
        }
    }
}

任何人都可以提出更好的解决方案吗?

4

1 回答 1

4
$picked  = array(1, 3, 5);
$theData = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $numCols = count($data);
        $row     = array();
        for($c=0; $c < $numCols; $c++)
            if(in_array($c, $picked))
                $row[] = $data[$c];
        $theData[] = $row;
    }
    fclose($handle);
}

编辑,根据 OP 请求

在这里,我们将第一行的列名映射为用于选择这些列的整数,而不需要列的数字标识符。未经测试,但我想它已经接近了。

$names      = array('Heading 1', 'Heading 2', 'Heading 3');
$picked     = array();
$theData    = array();
$isFirstRow = true;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $numCols = count($data);
        $row     = array();

        // process the first row to select columns for extraction
        if($isFirstRow) {
            for($c=0; $c<$numCols; $c++)
                if(!in_array($data[$c], $names)
                    continue;
                else
                    $picked[] = $c;
            $isFirstRow = false;
        }

        // process remaining rows
        else {
            for($c=0; $c < $numCols; $c++)
                if(in_array($c, $picked))
                    $row[] = $data[$c];
            $theData[] = $row;
        }
    }
    fclose($handle);
}
于 2013-01-22T06:08:27.563 回答