2013-01-22 51 views
0

我想從PHP使用csv只選擇某些列。目前我正在使用:只有從數組中使用PHP獲取選定的列

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

任何人都可以提出任何更好的解決方案嗎?

回答

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

編輯,每個操作要求

下面我們就從第一行的列名映射到用於選擇這些列,而不是需要列的數字標識符整數。未經測試,但我想它很接近。

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

您是否認爲可以轉動它以便可以使用列名而不是數字。 – Vish

+0

是的,我認爲你可以在第一行上運行,在處理剩下的行之前將名字映射到列號。 – quickshiftin

+0

你可以請更新解決方案。 – Vish