如果您不关心转换的深度级别,我认为对您来说最简单的选择就是array_dot
辅助函数。如果您想要更精细地控制递归的深度,以及是否有点分隔的数组键,我已经编写了一个可以做到这一点的集合宏。通常collect($array)->collapse()
维护字符串键,但非增量数字键仍然会丢失,即使强制类型为字符串。我最近需要维护它们。
把它放在你的AppServiceProvider::boot()
方法中:
/**
* Flatten an array while keeping it's keys, even non-incremental numeric ones, in tact.
*
* Unless $dotNotification is set to true, if nested keys are the same as any
* parent ones, the nested ones will supersede them.
*
* @param int $depth How many levels deep to flatten the array
* @param bool $dotNotation Maintain all parent keys in dot notation
*/
Collection::macro('flattenKeepKeys', function ($depth = 1, $dotNotation = false) {
if ($depth) {
$newArray = [];
foreach ($this->items as $parentKey => $value) {
if (is_array($value)) {
$valueKeys = array_keys($value);
foreach ($valueKeys as $key) {
$subValue = $value[$key];
$newKey = $key;
if ($dotNotation) {
$newKey = "$parentKey.$key";
if ($dotNotation !== true) {
$newKey = "$dotNotation.$newKey";
}
if (is_array($value[$key])) {
$subValue = collect($value[$key])->flattenKeepKeys($depth - 1, $newKey)->toArray();
}
}
$newArray[$newKey] = $subValue;
}
} else {
$newArray[$parentKey] = $value;
}
}
$this->items = collect($newArray)->flattenKeepKeys(--$depth, $dotNotation)->toArray();
}
return collect($this->items);
});
然后你可以打电话collect($a)->flattenKeepKeys(1, true);
并取回你所期望的。