Created
September 3, 2020 20:00
-
-
Save htuscher/39d340b4cf5729976aaa8c61ac48052f to your computer and use it in GitHub Desktop.
Doctrine DBAL Fetchmode helper FETCH_KEY_PAIR FETCH_GROUP
This file contains hidden or 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 declare(strict_types=1); | |
namespace Shopware\Core\Framework\DataAbstractionLayer\Doctrine; | |
class FetchModeHelper | |
{ | |
/** | |
* User-land implementation of PDO::FETCH_KEY_PAIR | |
*/ | |
public static function keyPair(array $result): array | |
{ | |
$firstRow = current($result); | |
if (empty($firstRow)) { | |
return $result; | |
} | |
list($keyName, $valueName) = array_keys($firstRow); | |
return array_combine( | |
array_column($result, $keyName), | |
array_column($result, $valueName) | |
); | |
} | |
/** | |
* User-land implementation of PDO::FETCH_GROUP | |
*/ | |
public static function group(array $result): array | |
{ | |
$firstRow = current($result); | |
if (empty($firstRow)) { | |
return $result; | |
} | |
$dataKeys = array_keys($firstRow); | |
$groupKey = array_shift($dataKeys); | |
$rows = []; | |
foreach ($result as $row) { | |
$index = $row[$groupKey]; | |
unset($row[$groupKey]); | |
$rows[$index][] = $row; | |
} | |
return $rows; | |
} | |
/** | |
* User-land implementation of PDO::FETCH_GROUP|PDO::FETCH_UNIQUE | |
*/ | |
public static function groupUnique(array $result): array | |
{ | |
$firstRow = current($result); | |
if (empty($firstRow)) { | |
return $result; | |
} | |
$dataKeys = array_keys($firstRow); | |
$groupKey = array_shift($dataKeys); | |
$rows = []; | |
foreach ($result as $row) { | |
$index = $row[$groupKey]; | |
unset($row[$groupKey]); | |
$rows[$index] = $row; | |
} | |
return $rows; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment