PHP code example of seankndy / phpcsv

1. Go to this page and download the library: Download seankndy/phpcsv library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

seankndy / phpcsv example snippets


use SeanKndy\CSV\CSV;

$csv = new CSV('file.csv');
$csv->join(
    new CSV('other_file.csv'),
    function ($r1, $r2) {
        return ($r1->get('id') == $r2->get('fid'));
    },
    ['user'],
    ['username']
));
$csv->getRecords()->dump();

use SeanKndy\CSV\CSV;

foreach (new CSV('file.csv', ['preload' => false])->getRecords() as $record) {
    print_r($record->getAll());
}

use SeanKndy\CSV\CSV;
use SeanKndy\CSV\Record;
use SeanKndy\CSV\Mutators\Mutator;

$csv = new CSV('customers.csv');
$csv->addMutator(new class extends Mutator {
    public function mutate(Record $record) {
        $rateGroups = preg_split('/,\s*/', $record->get('Rate Group(s)'));
        $billingFrequency = preg_split('/,\s*/', $record->get('Billing Frequency');

        if (count($rateGroups) > count($billingFrequency)) {
            // ex: if Rate Group(s) is '500,501,502' and Billing Frequency is '12'
            // then this would update Billing Frequency to be '12,12,12' to pair
            // with each of the Rate Group(s)
            for ($i = count($billingFrequency); $i < count($rateGroups); $i++) {
                $billingFrequency[] = $billingFrequency[0];
            }
            $record->set('Billing Frequency', implode(',', $billingFrequency));
        } else if (count($rateGroups) < count($billingFrequency)) {
            $billingFrequency = array_splice($billingFrequency, count($rateGroups));
            $record->set('Billing Frequency', implode(',', $billingFrequency));
        }

        return $record;
    }
});