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

问题描述 投票:0回答:2

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

这是我出色的代码。

$myArray = Arr::only($targetArray, ["title", "shortDesc"]);
arrays laravel helper
2个回答
0
投票

您可以为此使用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();

2
投票

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

不,仅使用Arr :: only函数无法实现您所需要的。您将需要更多。

© www.soinside.com 2019 - 2024. All rights reserved.