1、现有的数组结构如下,其键名为小写字母加下划线的形式。
[ [ [id] => 97 [theme_id] => vogue [version] => [asset_key] => assets/iconfont/iconfont.css [mime_type] => text/plain [category] => unknown [schema] => [created_at] => 2022-01-20 10:05:24 [updated_at] => 2022-01-20 10:05:24 ] [ [id] => 98 [theme_id] => vogue [version] => [asset_key] => assets/iconfont/iconfont.js [mime_type] => text/plain [category] => unknown [schema] => [created_at] => 2022-01-20 10:05:24 [updated_at] => 2022-01-20 10:05:24 ] ]
2、期望将数组键名调整为驼峰的形式,传统的方式就是基于 foreach 遍历,生成一个新的键名为驼峰形式的数组。这一次计划基于函数 array_map 实现。为数组的每个元素应用回调函数。
public function __invoke($rootValue, array $args, GraphQLContext $context, ResolveInfo $resolveInfo)
{
$themeId = $rootValue['themeAssets']['theme_id'];
$themeAssets = ThemeAsset::where('theme_id', $themeId)->get()->toArray();
$func = function($themeAsset) {
return [
'id' => $themeAsset['id'],
'themeId' => $themeAsset['theme_id'],
'version' => $themeAsset['version'],
'content' => $themeAsset['content'],
'key' => str_replace("//", "/", $themeAsset['asset_key']),
'mimeType' => $themeAsset['mime_type'],
'category' => $themeAsset['category'],
'schema' => $themeAsset['schema'],
'createdAt' => $themeAsset['created_at'],
'updatedAt' => $themeAsset['updated_at'],
];
};
$themeAssets = array_map($func, $themeAssets);
return $themeAssets;
}
3、转换后的数组结构如下,其键名为驼峰形式。如图1
[ [ [id] => 97 [themeId] => vogue [version] => [key] => assets/iconfont/iconfont.css [mimeType] => text/plain [category] => unknown [schema] => [createdAt] => 2022-01-20 10:05:24 [updatedAt] => 2022-01-20 10:05:24 ] [ [id] => 98 [themeId] => vogue [version] => [key] => assets/iconfont/iconfont.js [mimeType] => text/plain [category] => unknown [schema] => [createdAt] => 2022-01-20 10:05:24 [updatedAt] => 2022-01-20 10:05:24 ] ]
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/250319.html
