PHP code example of heliomarpm / linq-php

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

    

heliomarpm / linq-php example snippets




use HeliomarPM\LinqPHP\LinqPHP;

$data = [
  ['id' => 1, 'name' => 'John', 'age' => 25, 'status' => 'active', 'city' => 'London'],
  ['id' => 2, 'name' => 'Jane', 'age' => 30, 'status' => 'pending', 'city' => 'New York'],
  ['id' => 3, 'name' => 'John', 'age' => 35, 'status' => 'inactive', 'city' => 'Paris'],
];

$linq = LinqPHP::from($data);


// Filtro simples
$result = LinqPHP::from($data)
    ->where(['age', '>', 25])
    ->toArray();

// Múltiplos filtros e operadores (startswith, endswith, contains, in)
$result = LinqPHP::from($data)
    ->where([
        ['age', '>=', 25],
        ['status', 'in', ['active', 'pending']],
        ['name', 'startswith', 'J']
    ])
    ->toArray();

// Usando Closures (funções anônimas)
$result = LinqPHP::from($data)
    ->where(fn($item) => $item['id'] % 2 !== 0)
    ->toArray();

// Seleciona colunas específicas
$result = LinqPHP::from($data)
    ->select(['name', 'status'])
    ->toArray();

// Retorna apenas os registros únicos
$result = LinqPHP::from($data)
    ->select(['name'])
    ->distinct()
    ->toArray();

$users = [
    ['id' => 1, 'name' => 'John', 'course_id' => 10],
    ['id' => 2, 'name' => 'Jane', 'course_id' => 20],
];

$courses = [
    ['id_course' => 10, 'course_name' => 'PHP 8'],
    ['id_course' => 20, 'course_name' => 'Clean Code'],
];

$result = LinqPHP::from($users)
    ->join($courses, JoinType::INNER, ['course_id' => 'id_course'])
    ->toArray();

$vendas = [
    ['vendedor' => 'João', 'valor' => 100],
    ['vendedor' => 'Maria', 'valor' => 200],
    ['vendedor' => 'João', 'valor' => 150],
];

// Agrupa por vendedor e soma os valores
$result = LinqPHP::from($vendas)
    ->groupBy(['vendedor'], ['sum' => ['valor']])
    ->toArray();

// Ordena por uma chave simples
$result = LinqPHP::from($data)
    ->orderByKey('age', 'desc')
    ->toArray();

// Ordenação múltipla
$result = LinqPHP::from($data)
    ->orderBy(['name' => 'asc', 'age' => 'desc'])
    ->toArray();

$linq = LinqPHP::from($data)->where(['age', '>', 20]);

// Retorna um array tradicional
$array =$linq->toArray();

// Retorna um stdClass contendo metadados de performance
$obj =$linq->toObject();
echo $obj->count; // Quantidade de registros
echo $obj->elapsedTime; // Tempo de execução
echo $obj->memoryUsed; // Memória gasta
print_r($obj->rows); // Os dados em si
bash
composer