Skip to content

Commit

Permalink
grouping
Browse files Browse the repository at this point in the history
  • Loading branch information
rafageist committed Jan 17, 2024
1 parent d403152 commit 12b27e1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 4 deletions.
37 changes: 37 additions & 0 deletions examples/grouping.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?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->formatTXT(true);

// 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->formatTXT(true);

4 changes: 0 additions & 4 deletions src/matrix.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,10 +88,6 @@ public function __construct(array $matrix)
*/
public function validateMatrix(array $matrix): void
{
if (empty($matrix) || !is_array($matrix[0]) || empty($matrix[0])) {
throw new InvalidArgumentException('Matrix must have at least one row with string headers');
}

$numColumns = count($matrix[0]);
foreach ($matrix as $row) {
if (!is_array($row) || count($row) !== $numColumns) {
Expand Down

0 comments on commit 12b27e1

Please sign in to comment.