簡體   English   中英

僅使用PHP從數組中獲取選定的列

[英]Only get selected columns from array using 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] );
        }
    }
}

誰能提出更好的解決方案?

$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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM