Laravel Collections是否有办法使用键“命名空间”展平数组。类似的东西:
$a = collect([
'id' => 1,
'data' => [
'a' => 2,
'b' => 3
]
]);
$a = $a->flattenWithKeysNamespace(); // <-- this does not exists
// Should returns:
// ['a' => 1, 'data.b' => 2, 'data.c' => 3]; // <-- I would like this.
我知道我可以在原始PHP中执行此操作,或者使用Collection函数的某些程序集,但有时我会错过Laravel Collection文档中的内容。那么使用Collection函数有一个简单的方法吗?
答案 0 :(得分:0)
如果您不关心转换的深度级别,我认为最简单的选择就是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);
并取回您期待的内容。