简体   繁体   中英

Only get selected columns from array using PHP

I am trying to select only certain columns from a csv using PHP. Currently I am using:

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

Can anyone suggest any better solutions?

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

Edit, per OP request

Here we map column names from the first row into integers used to select those columns, rather than require the numeric identifier for the column. Untested, but I imagine it's close.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM