PHP Classes

PHP Group By Array: Group bidimensional arrays by a given element

Recommend this page to a friend!
  Info   View files Example   View files View files (3)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Ratings Unique User Downloads Download Rankings
Not enough user ratingsTotal: 182 This week: 1All time: 8,690 This week: 560Up
Version License PHP version Categories
group-by 1.0GNU General Publi...5.4PHP 5, Data types
Description 

Author

This class can broup bidimensional arrays by a given element.

It can take as parameter an array that contains a set of arrays with element values.

The class sorts the array grouping it by the elements of the set of arrays in a given positions similar to SQL GROUP BY clause.

Multiple elements may be used to group the array.

The class returns an array with the grouped elements containing two values: the first with the grouping key values and another with an array with remaining values.

Innovation Award
PHP Programming Innovation award nominee
September 2015
Number 11
GROUP BY is a SQL clause that allows grouping query results by values of certain result columns.

This package implements the group by SQL clause logic but applies it to bidimensional arrays.


Manuel Lemos
Picture of Willy Svenningsson
  Performance   Level  
Name: Willy Svenningsson <contact>
Classes: 1 package by
Country: Sweden Sweden
Age: 76
All time rank: 419626 in Sweden Sweden
Week rank: 411 Up5 in Sweden Sweden Up
Innovation award
Innovation award
Nominee: 1x

Example

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <?php
       
// This example results in
        // 1 Html table with some pretty hierarchy
        // 2 "pretty" array
        // 3 plain print_r of result
       
include "GroupBy.class.php";

       
$dataRows = [
                [
1, "Andy", "PHP", "4"],
                [
1, "Andy", "C#", "6"],
                [
2, "Josh", "C#", "6"],
                [
2, "Josh", "ASP", "4"],
                [
1, "Andy", "SQL", "6"],
                [
3, "Steve", "SQL", "2"],
                [
4, "self", "SQL", "30"],
                [
4, "self", "Smalltalk", "5"],
                [
4, "self", "C", "33"],
                [
4, "self", "Swedish", "65"]
        ];
       
// Group on the third column
       
$res = (new GroupBy())->groupBy($dataRows, [ 2 ]);

       
// Group on Years and Language
// $res = (new GroupBy())->groupBy($dataRows, [ 3, 2 ]);
        // You get an array back
        // Each row contains two arrays
        // First array: The key as an array of columns values
        // Second array: An array of all rows to this key

       
        // The above call [ 2 ] will result in
        // (pasted from output of this test)
       
$x = [
                [
                        [
"ASP"],
                        [
                                [
"2", "Josh", "4"]
                        ]
                ],
                [
                        [
"C"],
                        [
                                [
"4", "self", "33"]
                        ]
                ],
                [
                        [
"C#"],
                        [
                                [
"1", "Andy", "6"],
                                [
"2", "Josh", "6"]
                        ]
                ],
                [
                        [
"PHP"],
                        [
                                [
"1", "Andy", "4"]
                        ]
                ],
                [
                        [
"SQL"],
                        [
                                [
"1", "Andy", "6"],
                                [
"3", "Steve", "2"],
                                [
"4", "self", "30"]
                        ]
                ],
                [
                        [
"Smalltalk"],
                        [
                                [
"4", "self", "5"]
                        ]
                ],
                [
                        [
"Swedish"],
                        [
                                [
"4", "self", "65"]
                        ]
                ]
        ];
       
// Usage (dummy)
       
foreach ($res as $aGroup)
        {
           
$groupKey = $aGroup[0];
           
$groupRows = $aGroup[1];
            foreach (
$groupRows as $groupRow)
            {
               
// We got all columns in $groupRow
                // (And the key cols in $groupKey
           
}
        }
       
// Display as a HTML table

       
echo "<code><table border='1'>";
       
$runningLinenumber = 1;
        foreach (
$res as $aGroup)
        {
           
$groupKey = $aGroup[0];
           
$groupRows = $aGroup[1];
           
// first row. calc rowspan
           
echo "<tr>";
            echo
"<td>" . $runningLinenumber++ . "</td>"; // optional. but nice for user row interaction
           
echo "<td rowspan='" . count($groupRows) . "' valign=\"top\">" . implode(",", $groupKey) . "</td>";
            echo
"<td>" . implode("</td><td>", $groupRows[0]) . "</td>";
            echo
"</tr>";
           
// end first row
           
for ($r = 1; $r < count($groupRows); ++$r)
            {
               
$groupRow = $groupRows[$r];
                echo
"<tr>";
                echo
"<td>" . $runningLinenumber++ . "</td>"; // optional
               
echo "<td>" . implode("</td><td>", $groupRow) . "</td>";
                echo
"</tr>";
            }
            echo
"</tr>";
        }
        echo
"</table></code>";

// Display as php array initial (copy and paste from the output)

       
echo '<pre>';
        echo
"[\n";
       
$keyAndData = [];
        for (
$grpNr = 0; $grpNr < count($res); ++$grpNr)
        {
           
$groupKey = $res[$grpNr][0];
           
$keyTTY = '"' . implode('","', $groupKey) . '"';
            echo
" [\n";
            echo
" [" . $keyTTY . "],\n";
            echo
" [\n";
           
$groupRows = $res[$grpNr][1];
            for (
$rowNr = 0; $rowNr < count($groupRows); ++$rowNr)
            {
               
$groupRow = $groupRows[$rowNr];
               
$aRow = '"' . implode('","', $groupRow) . '"';
                echo
" [" . $aRow . "]";
                if (
$rowNr != count($groupRows) - 1)
                    echo
",\n";
                else
                    echo
"\n";
            }
            echo
" ]\n";
            echo
" ]";
            if (
$grpNr != count($res) - 1)
                echo
",\n";
            else
                echo
"\n";
        }
        echo
"]\n";
        echo
print_r($res, true);
        echo
'</pre>';
       
?>
</body>
</html>


Details

GroupBy class - Generate hierarchical array on resultsets or similar using the SQL GROUP BY metaphor method: groupBy usage: groupBy($rows , $keyColsIndex) params: $rows = an array of arrays of columns like a resultset from SQL $keyColsIndex = an array of column index specifing the key. [0, nrcols-1] how to use the output: [$res = (new GroupBy())->groupBy($rows, $keyColsIndex);] foreach ($res as $aGroup) { $groupKey = $aGroup[0]; $groupRows = $aGroup[1]; // How many lines is given by count($groupRows) foreach ($groupRows as $groupRow) { // We got all columns in $groupRow // (And the key cols in $groupKey) // (And you can GroupBy on the $groupRow to get even more hierarchy) } // Here we can do any SQL aggregate functions on '$groupRows' like COUNT, MAX, MIN etc } This is the only method in the class. returns: A sorted array of arrays. Each item has an array for the 'grouby' values and an array with arrays of column values for this group [ [ [groubyols,], [ [restcols,],...] ], ] like [ [ ["A",1], [ ["23","14"],["19",4"] ] ], [ ["B",2], [ ["22","54"],["35","41"],["0","99] ] ] ] for the (unsorted!) input [ ["A","1","23","14"], ["B","2","22","54"], ["B","2","35","41"], ["A","1","19","4"], ["B","2","0","99"] ] and call ->groupBy(data, [0, 1])

  Files folder image Files  
File Role Description
Plain text file GroupBy.class.php Class The very class
Accessible without login Plain text file index.php Example Test
Accessible without login Plain text file readme.txt Doc. Readme

 Version Control Unique User Downloads Download Rankings  
 0%
Total:182
This week:1
All time:8,690
This week:560Up