squidit / data-array-mapper
Squid IT - 数据库 ResultSet 到多维数组映射器
v0.2.3
2021-05-06 14:04 UTC
Requires
- php: ^7.3 || ^8.0
Requires (Dev)
- phpunit/phpunit: ^8
This package is auto-updated.
Last update: 2024-09-06 21:57:41 UTC
README
将数据库结果集转换为多维数组
此包允许您快速将数据库结果集转换为多维数组。当您需要输出嵌套 JSON 时,这非常有用。
示例数据集 & 最终结果
<?php $resultSet = [ [ 'userId' => 3, 'userName' => 'MoròSwitie', 'age' => 37, 'toyId' => 7, 'toyType' => 'car', 'toyName' => 'Rover', 'placeId' => 33, 'placeName' => 'Australia', ], [ 'userId' => 3, 'userName' => 'MoròSwitie', 'age' => 37, 'toyId' => 7, 'toyType' => 'car', 'toyName' => 'Rover', 'placeId' => 34, 'placeName' => 'New Zealand', ] ]; $finalResult = [ 3 => [ 'userId' => 3, 'userName' =>'MoròSwitie', 'age' => 37, 'toys' => [ 7 => [ 'toyId' => 7, 'toyType' => 'car', 'toyName' => 'Rover', 'placesToyVisited' => [ 33 => [ 'placeId' => 33, 'placeName' => 'Australia', ], 34 => [ 'placeId' => 34, 'placeName' => 'New Zealand', ], ] ] ] ] ];
示例用法
在我们将结果集映射到新结构之前,我们需要描述我们的最终结果应该是什么样子。我们还需要提供我们的枢纽点路径。
我们将使用 "点" 表示法来描述我们的枢纽点。需要注意的是,在 $pivotPoints 数组中必须存在 "['root']" 键。
枢纽点将被用于分组结果集。
经验法则
对于您的 $resultStructure 数组中的每个键,如果您不是列,则需要指定一个枢纽点。在下面的 $resultStructure 数组中,我们得到了 3 个枢纽点。
- "['root']"(这个键实际上不在我们的数组中,但我们需要定义它)
- "toys"
- "placesToyVisited"
<?php $resultStructure = [ 'userId', 'userName', 'age', 'toys' => [ 'toyId', 'toyType', 'toyName', 'placesToyVisited' => [ 'placeId', 'placeName', ] ] ]; $pivotPoints = [ '[root]' => 'userId', 'toys' => 'toyId', 'toys.placesToyVisited' => 'placeId', ];
要得到我们的最终结果,我们需要这样做
<?php // Make sure composer autoload has loaded use SquidIT\Data\ResultSetToArray\Mapper; $parsedStructure = Mapper::parseStructure($resultStructure, $pivotPoints); $mappedData = Mapper::mapData($resultSet, $parsedStructure);
如果我们不希望我们的枢纽点数据以枢纽点 ID 值为前缀,我们可以在 Mapper::mapData
方法中添加一个额外的参数 "false"。
这将确保当使用 json_encode 时,生成的对象将包含所有枢纽点数据的数组。
<?php // Make sure composer autoload has loaded use SquidIT\Data\ResultSetToArray\Mapper; $parsedStructure = Mapper::parseStructure($resultStructure, $pivotPoints); $mappedData = Mapper::mapData($resultSet, $parsedStructure, false);
指定不同的列名
在映射的数据结果中,可以使用不同的列名。为此,我们可以指定我们想要的新列的名称。
<?php $resultStructure = [ 'userId' => 'accountId', // dataset column = 'userId', output would be 'accountId' 'userName' => 'accountName', 'age' => 'accountCreationDate', 'toys' => [ 'toyId', 'toyType' => 'specimen', 'toyName', 'placesToyVisited' => [ 'placeId', 'placeName', ] ] ]; $pivotPoints = [ '[root]' => 'userId', 'toys' => 'toyId', 'toys.placesToyVisited' => 'placeId', ];