PHP code example of entreya / csvquery

1. Go to this page and download the library: Download entreya/csvquery 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/ */

    

entreya / csvquery example snippets



Entreya\CsvQuery\Core\CsvQuery;

// 1. Point to your CSV
$csv = new CsvQuery('/data/sales.csv', [
    'indexDir' => '/data/indexes',   // optional — defaults to CSV directory
    'workers'  => 8,                 // optional — parallel indexing workers
]);

// 2. Create indexes (one-time, ~400 k rows/sec)
$csv->createIndex(['STATUS', 'CATEGORY']);

// 3. Query with a fluent API
$results = $csv->find()
    ->select(['ID', 'NAME', 'STATUS'])
    ->where(['STATUS' => 'active'])
    ->andWhere(['>', 'SCORE', 80])
    ->orderBy(['SCORE' => SORT_DESC])
    ->limit(100)
    ->all();

// 4. Stream large result sets with generators
foreach ($csv->find()->where(['CATEGORY' => 'premium'])->each() as $row) {
    echo $row['NAME'] . "\n";
}

// 5. Aggregations
$count = $csv->find()->where(['STATUS' => 'active'])->count();
$total = $csv->find()->groupBy('CATEGORY')->sum('AMOUNT');

// Comparison operators
$csv->find()->where(['>', 'PRICE', 100])->all();
$csv->find()->where(['<=', 'AGE', 30])->all();
$csv->find()->where(['!=', 'STATUS', 'deleted'])->all();

// BETWEEN
$csv->find()->where(['BETWEEN', 'AGE', 18, 65])->all();

// IN
$csv->find()->where(['IN', 'CATEGORY', ['A', 'B', 'C']])->all();

// LIKE
$csv->find()->where(['LIKE', 'NAME', '%john%'])->all();

$csv->find()
    ->where(['OR',
        ['STATUS' => 'active'],
        ['AND',
            ['>', 'SCORE', 90],
            ['TYPE' => 'vip']
        ]
    ])
    ->all();

// Simple aggregations
$avg   = $csv->find()->where(['STATUS' => 'active'])->average('SCORE');
$min   = $csv->find()->min('PRICE');
$max   = $csv->find()->max('PRICE');
$sum   = $csv->find()->sum('AMOUNT');
$count = $csv->find()->count();

// Group-by counts
$stats = $csv->find()->groupBy('CATEGORY')->count();
// → ['A' => 1200, 'B' => 890, 'C' => 450]

// Insert a single row
$csv->insert(['ID' => '999', 'NAME' => 'Alice', 'STATUS' => 'active']);

// Batch insert
$csv->batchInsert([
    ['ID' => '1000', 'NAME' => 'Bob',   'STATUS' => 'active'],
    ['ID' => '1001', 'NAME' => 'Carol', 'STATUS' => 'pending'],
]);

// Update rows (sidecar — does not rewrite CSV)
$csv->update(
    ['STATUS' => 'inactive'],         // SET
    ['ID' => '123']                   // WHERE
);

// Add a virtual column
$csv->addColumn('REGION', 'UNKNOWN');

// Inspect the generated SQL-like representation
$command = $csv->find()
    ->select(['ID', 'NAME'])
    ->where(['STATUS' => 'active'])
    ->orderBy(['NAME' => SORT_ASC])
    ->limit(10)
    ->createCommand();

echo $command->getQuery();
// → SELECT ID, NAME FROM `sales` WHERE `STATUS` = 'active' ORDER BY NAME ASC LIMIT 10

// Explain the execution plan
$plan = $csv->find()->where(['STATUS' => 'active'])->explain();
// → ['strategy' => 'IndexScan', 'index' => 'STATUS', ...]

// each() returns a Generator — only one row is in memory at a time
foreach ($csv->find()->where(['STATUS' => 'active'])->each() as $row) {
    // $row is a Row object with ArrayAccess
    echo $row['NAME'];

    // Or use model methods
    $cell = $row->getCell('SCORE');
    echo $cell->asInt();          // type-safe cast
    echo $cell->isNumeric();      // true/false
}

// Index results by a column
$byId = $csv->find()
    ->indexBy('ID')
    ->all();
// → ['42' => Row, '43' => Row, ...]

// Return plain arrays instead of Row objects
$arrays = $csv->find()->asArray()->all();

use Entreya\CsvQuery\Core\CsvQuery;

$csv = new CsvQuery(string $csvPath, array $options = []);

$query = $csv->find();

// Hash format (implicit AND)
->where(['STATUS' => 'active', 'TYPE' => 'premium'])

// Operator format
->where(['>', 'SCORE', 80])
->where(['BETWEEN', 'AGE', 18, 65])
->where(['IN', 'CATEGORY', ['A', 'B', 'C']])
->where(['LIKE', 'NAME', '%john%'])

// Nested logical groups
->where(['OR',
    ['STATUS' => 'active'],
    ['AND',
        ['>', 'SCORE', 90],
        ['TYPE' => 'vip']
    ]
])

$row = $csv->find()->one();

// Array access
echo $row['NAME'];

// Magic property
echo $row->NAME;

// Model methods
$row->getColumn('NAME');         // → Column object
$row->getCell('NAME');           // → Cell object
$row->toAssociativeArray();      // → ['NAME' => 'Alice', ...]
$row->getLineNumber();           // → int|null
$row->toJson();                  // → JSON string

$cell = $row->getCell('SCORE');

$cell->getValue();               // raw value
$cell->asInt();                  // (int) cast with default
$cell->asFloat();                // (float) cast with default
$cell->asBool();                 // 1/true/yes/on/y → true
$cell->asString();               // (string) cast
$cell->isEmpty();                // null or ''
$cell->isNumeric();              // is_numeric()

// Inline validation
$result = $cell->validate(['

$col = $row->getColumn('NAME');

$col->getValue();
$col->getName();                 // 'NAME'
$col->getIndex();                // column position (0-based)
$col->getCell();                 // → Cell
$col->trim();
$col->toUpper();
$col->toLower();
bash
php scripts/build.php           # Current OS/arch
php scripts/build.php --all     # All platforms