如何使用 Arr::only 助手重命名数组的键?

How to rename key of array with Arr::only helper?

我正在使用 Arr::only 通过键从数组中获取值,但是我需要重命名 ShortDesc 键以使用蛇形而不是驼峰式。这可以用 Arr::only 还是我需要使用 array_map?

这是我的绝妙代码。

$myArray = Arr::only($targetArray, ["title", "shortDesc"]);

查看代码:https://github.com/illuminate/support/blob/master/Arr.php#L367

不,仅使用 Arr::only 功能无法实现您的需求。 你还需要一些。

您可以为此使用 collections 而不是辅助方法:

$array = [
    'title'          => 'The title',
    'shortDesc'      => 'The short description',
    'someOtherValue' => 'foobar',
];

$newArray = collect($array)
    ->only('title', 'shortDesc')
    ->keyBy(function ($item, $key) {
        return Str::snake($key);
    })->toArray();