如何 return 索引中的字符串 Laravel 7

How to return a string in indices that are array in Laravel 7

我想知道如何 return 一个字符串,对于我的请求的任何部分,它是一个数组。
该请求可以包含任何密钥,因此我无法对其进行硬编码。

到目前为止我所做的示例。

$request = [
    'empresaId' => '2',
    'entidadeId' => [
        '507-2',
        '1422-2',
    ],
    'dataInicio' => '2021-05-27',
    'dataFim' => '2021-05-31',
];

$requestFiltered = Arr::where($request->all(), function($value, $key) { 
    if (!is_null($value) && ($key != '_token')) {
        if (is_array($value)) {
            return collect($value)->implode(',');
        }
        return $value;
    }
});

这 return 数据不符合我的预期。
我不确定我做错了什么。

这是我希望数组 returned 的示例。

[
    'empresaId' => '2',
    'entidadeId' => '507-2,1422-2',
    'dataInicio' => '2021-05-27',
    'dataFim' => '2021-05-31',
]

如果我没记错的话,就是这样:

$requestFiltered = Arr::where($request, function($value){ 
    if(is_array($value)){
        return $value;
    }
});

你快到了,你可以使用 map 而不是 where

where 不用于改变数据,它只是查询数据,所以你只应该 return 闭包中的布尔值。
maptransform 将改变您的数据。

$requestFiltered = collect($request->all())->map(function ($item, $key) {
    // Ignore tokens.
    if (Str::endsWith($key, '_token')) {
        return;
    }

    // Check for arrays, then implode.
    if (is_array($item)) {
        return implode(',', $item);
    }

    return $item;
})