Skip to content

Instantly share code, notes, and snippets.

@sfaut
Created April 9, 2023 10:31
Show Gist options
  • Save sfaut/f69039d7c00809c836ed9c347b176d26 to your computer and use it in GitHub Desktop.
Save sfaut/f69039d7c00809c836ed9c347b176d26 to your computer and use it in GitHub Desktop.
PHP pivots an array of records
/*
Pivots an array of records
Author : sfaut <https://github.com/sfaut>
Publication date : 2023-04-09
Tested with PHP 8.2.4
*/
function array_pivot(array $data, string $key_rows, string $key_columns, string $key_values, mixed $default_value = null): array
{
// Transtyping
foreach ($data as $i => $record) {
// Because records are more array oriented
// and PHP has many more array helpers than object helpers
$data[$i] = (array)$record;
}
// Indexing values
$index = [];
foreach ($data as $record) {
$index[$record[$key_rows]][$record[$key_columns]] = $record[$key_values];
}
// Columns series
$rows = array_column($data, $key_rows);
$rows = array_unique($rows);
// Rows series
$columns = array_column($data, $key_columns);
$columns = array_unique($columns);
// Pivot
$matrix = [];
foreach ($rows as $row) {
$record = [];
foreach ($columns as $column) {
$record[$row][$column] = $index[$row][$column] ?? $default_value;
}
$matrix[] = $record;
}
return $matrix;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment