PHP Classes

File: examples/grouping.php

Recommend this page to a friend!
  Classes of Rafa Rodriguez   Div PHP Matrix Library   examples/grouping.php   Download  
File: examples/grouping.php
Role: Example script
Content type: text/plain
Description: Example script
Class: Div PHP Matrix Library
Define matrices with dynamic cell calculations
Author: By
Last change: new features & phpstan level 9
Date: 5 months ago
Size: 688 bytes
 

Contents

Class file image Download
<?php

include __DIR__ . "/../src/matrix.php";

use
divengine\matrix;

// Create a matrix

$table = new matrix([
    [
"Product", "Count"],
   
//------------------
   
["Apple", 2],
    [
"Banana", 3],
    [
"Banana", 5],
    [
"Orange", 6],
    [
"Orange", 5],
    [
"Orange", 2],
    [
"Orange", 3],
]);

// Show the matrix
echo $table;

// Group by
$result = $table->groupBy([0], function($key, $group){
   
$sum = 0;
    foreach(
$group as $row){
       
$sum += $row[1];
    }
    return [
$key, $sum];
},
true);

echo
"\n";
$groupBy = new matrix(array_values($result));
$groupBy->addRow(["Product", "Total"], onTop: true);
echo
$groupBy;