Skip to content

Instantly share code, notes, and snippets.

@sfaut
Created March 23, 2024 16:16
Show Gist options
  • Save sfaut/946ef65fcfeb83906485e7b59b342d9f to your computer and use it in GitHub Desktop.
Save sfaut/946ef65fcfeb83906485e7b59b342d9f to your computer and use it in GitHub Desktop.
PHP pivots an array of records to an array of series or an array of series to an array of records
<?php
/*
Utility class that pivots an array of records to an array of series
or an array of series to an array of records
Author : sfaut <https://github.com/sfaut>
Publication date : 2024-03-23
Tested with PHP 8.3.3
*/
class SimplePivoter
{
/*
Returns a pivoted $data from records to series
Input :
[
['country' => 'France', 'capital' => 'Paris', 'continent' => 'Europa'],
['country' => 'Japan', 'capital' => 'Tokyo', 'continent' => 'Asia'],
]
Output :
[
'country' => ['France', 'Japan'],
'capital' => ['Paris', 'Tokyo'],
'continent' => ['Europa', 'Asia'],
]
*/
public static function recordsToSeries(array $data): array
{
$result = [];
foreach ($data as $record) {
foreach ($record as $key => $value) {
$result[$key][] = $value;
}
}
return $result;
}
/*
Returns a pivoted $data from series to records
Input :
[
'country' => ['France', 'Japan'],
'capital' => ['Paris', 'Tokyo'],
'continent' => ['Europa', 'Asia'],
]
Output :
[
['country' => 'France', 'capital' => 'Paris', 'continent' => 'Europa'],
['country' => 'Japan', 'capital' => 'Tokyo', 'continent' => 'Asia'],
]
*/
public static function seriesToRecords(array $data): array
{
$result = [];
foreach ($data as $key => $values) {
foreach ($values as $i => $value) {
$result[$i][$key] = $value;
}
}
return $result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment