仅使用PHP从数组中获取选定的列

时间:2013-01-22 04:55:02

标签: php

我试图使用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] );
        }
    }
}

有人可以建议任何更好的解决方案吗?

1 个答案:

答案 0 :(得分: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);
}