[英]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.