Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CRM_Utils_Array::asColumns() - Add helper to rotate a matrix (from rows to columns) #20788

Merged
merged 1 commit into from
Jul 7, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions CRM/Utils/Array.php
Original file line number Diff line number Diff line change
Expand Up @@ -983,6 +983,34 @@ public static function filterColumns($matrix, $columns) {
return $newRows;
}

/**
* Rotate a matrix, converting from row-oriented array to a column-oriented array.
*
* @param iterable $rows
* Ex: [['a'=>10,'b'=>'11'], ['a'=>20,'b'=>21]]
* Formula: [scalar $rowId => [scalar $colId => mixed $value]]
* @param bool $unique
* Only return unique values.
* @return array
* Ex: ['a'=>[10,20], 'b'=>[11,21]]
* Formula: [scalar $colId => [scalar $rowId => mixed $value]]
* Note: In unique mode, the $rowId is not meaningful.
*/
public static function asColumns(iterable $rows, bool $unique = FALSE) {
$columns = [];
foreach ($rows as $rowKey => $row) {
foreach ($row as $columnKey => $value) {
if (FALSE === $unique) {
$columns[$columnKey][$rowKey] = $value;
}
elseif (!in_array($value, $columns[$columnKey] ?? [])) {
$columns[$columnKey][] = $value;
}
}
}
return $columns;
}

/**
* Rewrite the keys in an array.
*
Expand Down
31 changes: 31 additions & 0 deletions tests/phpunit/CRM/Utils/ArrayTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,37 @@
*/
class CRM_Utils_ArrayTest extends CiviUnitTestCase {

public function testAsColumns() {
$rowsNum = [
['a' => 10, 'b' => 11],
['a' => 20, 'b' => 21],
['a' => 20, 'b' => 29],
];

$rowsAssoc = [
'!' => ['a' => 10, 'b' => 11],
'@' => ['a' => 20, 'b' => 21],
'#' => ['a' => 20, 'b' => 29],
];

$this->assertEquals(
['a' => [10, 20, 20], 'b' => [11, 21, 29]],
CRM_Utils_Array::asColumns($rowsNum)
);
$this->assertEquals(
['a' => [10, 20], 'b' => [11, 21, 29]],
CRM_Utils_Array::asColumns($rowsNum, TRUE)
);
$this->assertEquals(
['a' => ['!' => 10, '@' => 20, '#' => 20], 'b' => ['!' => 11, '@' => 21, '#' => 29]],
CRM_Utils_Array::asColumns($rowsAssoc)
);
$this->assertEquals(
['a' => [10, 20], 'b' => [11, 21, 29]],
CRM_Utils_Array::asColumns($rowsAssoc, TRUE)
);
}

public function testIndexArray() {
$inputs = [];
$inputs[] = [
Expand Down