Implementation of renaming array key names in PHP (based on function array_map)
1. The existing array structure is as follows, and its key name is the form of lowercase letters and underscores.
[
[
[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. It is expected to adjust the name of the array key to the hump form. The traditional way is to generate a new key in the form of a hump based on the foreach traversal. This time the plan is implemented based on the function array_map . Apply a callback function for each element of the array.
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. The converted array structure is as follows, and its key is called camel form. as shown in Figure 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
]
]
