PHP code example of betoalien / pardox-php

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

    

betoalien / pardox-php example snippets



PardoX\DataFrame;
use PardoX\IO;

// Load 100,000 rows — parallel Rust CSV parser
$df = DataFrame::read_csv('./sales_data.csv');
echo "Loaded " . number_format($df->shape[0]) . " rows\n";

// SIMD-accelerated arithmetic
$meanDiscount = $df->mean('discount');
echo sprintf("Mean discount: %.4f\n", $meanDiscount);

// Value frequency table
$stateCounts = $df->value_counts('state');
arsort($stateCounts);
foreach (array_slice($stateCounts, 0, 3, true) as $state => $count) {
    echo "  $state: $count\n";
}

// GroupBy aggregation
$grouped = $df->group_by('state', ['revenue' => 'sum', 'quantity' => 'mean']);

// Write to MySQL
$MYSQL = 'mysql://user:password@localhost:3306/mydb';
IO::executeMysql($MYSQL, 'CREATE TABLE IF NOT EXISTS sales (price DOUBLE, quantity DOUBLE)');
$rows = $df->to_mysql($MYSQL, 'sales', 'append');
echo "Written $rows rows to MySQL\n";

use PardoX\IO;

$rows = IO::write_sql_prdx(
    '/data/ventas_150m.prdx',
    'postgresql://user:pass@localhost:5432/mydb',
    'ventas',           // table must already exist
    'append',
    [],
    1000000             // rows per COPY batch
);
echo "Streamed " . number_format($rows) . " rows\n";
// Validated: 150,000,000 rows / 3.8 GB in ~1,032s at ~145k rows/s

// Single aggregation
$grouped = $df->group_by('category', ['revenue' => 'sum']);

// Multiple aggregations
$grouped = $df->group_by('state', [
    'revenue'  => 'sum',
    'price'    => 'mean',
    'quantity' => 'count',
]);

// String ops
$df->str_upper('name');
$df->str_lower('email');
$df->str_trim('description');
$df->str_contains('tag', 'php');
$df->str_replace('status', 'old', 'new');

// Date ops
$df->date_extract('created_at', 'year');   // → 'result_year'
$df->date_format('created_at', '%Y-%m');
$df->date_diff('end_date', 'start_date');
$df->date_add('created_at', 30, 'day');

$df->row_number('price');
$df->rank('revenue', 'dense');
$df->lag('price', 1);
$df->lead('price', 1);
$df->rolling_mean('price', 7);   // 7-period moving average

use PardoX\IO;

// Scan without loading — filter and collect on demand
$result = IO::lazy_scan_csv('./large_file.csv')
    ->select(['id', 'price', 'state'])
    ->filter('price', '>', 100.0)
    ->limit(10000)
    ->collect();

echo $result->shape[0] . " rows\n";

// Register a DataFrame and run SQL against it
$df = DataFrame::read_csv('./orders.csv');
$result = $df->sql('SELECT state, SUM(revenue) as total FROM df GROUP BY state');

use PardoX\IO;

// Write encrypted PRDX
IO::write_prdx_encrypted('./secure.prdx', $df, 'my-secret-key');

// Read back
$df = IO::read_prdx_encrypted('./secure.prdx', 'my-secret-key');

$contract = json_encode([
    'source'  => 'orders',
    'columns' => [
        'price'    => ['min' => 0.0, 'max' => 10000.0],
        'status'   => ['allowed_values' => ['active', 'pending', 'closed']],
        'customer' => ['nullable' => false],
    ]
]);

// Returns a new DataFrame with only conforming rows
$clean = $df->validate_contract($contract);
$violations = $df->contract_violation_count();
echo "$violations rows quarantined\n";

use PardoX\DataFrame;
use PardoX\IO;

// ── PostgreSQL ────────────────────────────────────────────────
$PG = 'postgresql://user:pass@localhost:5432/mydb';

$df = IO::read_sql($PG, 'SELECT * FROM orders WHERE status = \'active\'');
IO::executeSql($PG, 'CREATE TABLE orders_archive (id BIGINT, amount FLOAT, region TEXT)');

// COPY FROM STDIN auto-activated for > 10,000 rows
$rows = $df->to_sql($PG, 'orders_archive', 'append');

// Upsert — INSERT … ON CONFLICT DO UPDATE
$rows = $df->to_sql($PG, 'orders_archive', 'upsert', ['id']);

// ── MySQL ─────────────────────────────────────────────────────
$MY = 'mysql://user:pass@localhost:3306/mydb';

$df = IO::read_mysql($MY, 'SELECT * FROM products WHERE active = 1');
$rows = $df->to_mysql($MY, 'products_bak', 'append');
$rows = $df->to_mysql($MY, 'products_bak', 'upsert', ['id']);

// ── SQL Server ────────────────────────────────────────────────
$MS = 'Server=localhost,1433;Database=mydb;UID=sa;PWD=MyPwd;TrustServerCertificate=Yes';

$df = IO::read_sqlserver($MS, 'SELECT TOP 5000 * FROM dbo.transactions');
$rows = $df->to_sqlserver($MS, 'dbo.transactions_bak', 'upsert', ['id']); // MERGE INTO

// ── MongoDB ───────────────────────────────────────────────────
$MG = 'mongodb://admin:pass@localhost:27017';

$df = IO::read_mongodb($MG, 'mydb.orders');
$rows = $df->to_mongodb($MG, 'mydb.orders_archive', 'append');

$df = DataFrame::read_csv('./file.csv');
$df = DataFrame::read_csv('./file.csv', ['price' => 'Float64']);  // with schema
$df = IO::read_sql($pgConn, 'SELECT * FROM orders');
$df = IO::read_mysql($myConn, 'SELECT * FROM products');
$df = IO::read_sqlserver($msConn, 'SELECT TOP 100 * FROM dbo.t');
$df = IO::read_mongodb($mgConn, 'mydb.collection');

$df->shape      // [rows, cols]
$df->columns    // ['col1', 'col2', ...]
$df->dtypes     // ['col1' => 'Float64', ...]

$df->show(10);              // ASCII table (stdout)
$df->head(5);               // → DataFrame
$df->tail(5);               // → DataFrame
$df->iloc(0, 100);          // → DataFrame (rows 0–99)

$df->cast('quantity', 'Float64');
$df->fillna(0.0);
$df->round(2);
$df->mul('price', 'quantity');       // → DataFrame with 'result_mul'
$df->sub('revenue', 'cost');         // → DataFrame with 'result_sub'
$df->add('amount', 'tax');           // → DataFrame with 'result_add'
$df->std('column');                  // float
$df->min_max_scale('col');           // → DataFrame with 'result_minmax'
$df->sort_values('col', true);       // → DataFrame (ascending)
$df->sort_values('col', false, true);// → DataFrame (descending, GPU)

$df->group_by('category', ['revenue' => 'sum', 'price' => 'mean']);
$df->group_by('state', ['quantity' => 'count', 'revenue' => 'max']);

$df->row_number('price');
$df->rank('revenue', 'dense');
$df->lag('price', 1);
$df->lead('price', 1);
$df->rolling_mean('price', 7);

$df->str_upper('col');
$df->str_lower('col');
$df->str_trim('col');
$df->str_len('col');
$df->str_contains('col', 'pattern');
$df->str_replace('col', 'old', 'new');

$total   = $df['price'] * $df['quantity'];    // → Series
$net     = $df['revenue'] - $df['discount'];  // → Series
$df['total'] = $df['price'] * $df['quantity']; // assign new column

$df['col']->sum();     // float
$df['col']->mean();    // float
$df['col']->min();     // float
$df['col']->max();     // float
$df['col']->std();     // float
$df['col']->count();   // int

$df->value_counts('col');   // ['value' => count, ...]
$df->unique('col');         // ['val1', 'val2', ...]
$df->to_dict();             // [['col' => val, ...], ...]
$df->to_json();             // string
$df->tolist();              // [[val, val, ...], ...]

$df->to_prdx('./out.prdx');
$df->to_csv('./out.csv');
$df->to_sql($pgConn, 'table', 'append', ['id']);
$df->to_mysql($myConn, 'table', 'upsert', ['id']);
$df->to_sqlserver($msConn, 'dbo.table', 'append');
$df->to_mongodb($mgConn, 'db.collection', 'append');
IO::write_sql_prdx('file.prdx', $pgConn, 'table', 'append', [], 1000000);

IO::executeSql($pgConn, 'CREATE TABLE ...');
IO::executeMysql($myConn, 'DROP TABLE IF EXISTS ...');
IO::executeSqlserver($msConn, 'TRUNCATE TABLE dbo.staging');
IO::executeMongodb($mgConn, 'mydb', '{"drop": "col"}');
bash
composer 
ini
; php.ini
extension=ffi
ffi.enable=true