Created
March 23, 2024 16:16
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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