timdev / array-undot
一个用于规范化带点字符串键的数组的工具。['a.b' => 'c'] ==> ['a' => ['b' => 'c']]
0.1.2
2021-12-18 22:19 UTC
Requires
- php: ~8.0.0 || ~8.1.0
Requires (Dev)
- laminas/laminas-config-aggregator: ^1.5
- timdev/devtools: ^0.1
This package is auto-updated.
Last update: 2024-09-20 01:28:34 UTC
README
这是什么?
它将带点字符串键的数组规范化为不带点字符串键的数组。
例如,它将['a.b' => 'FOO']
转换为['a' => ['b' => 'FOO']]
。
为什么?
我在一个使用mezzio和一个laminas-config-aggregator的项目上工作,该项目将大量的配置数据合并到一个大型的嵌套数组中。有时,我想从本地配置文件中更改结构深处的一个值。
// myapp.local.php return [ // sometimes it's nicer (reading and writing) to do this: 'path.to.some.key' => 'value', // as opposed to this: 'path' => [ 'to' => [ 'some' => [ 'key' => 'value' ] ] ] ];
行为
Undotter::undot()
递归地遍历(深度优先)其参数,在遍历过程中构建一个新的数组。
use \TimDev\ArrayUndot\Undotter; /* Example 1: The basic idea: */ Undotter::undot(['a.b' => 'FOO']); // => ['a' => ['b' => 'FOO']] /* Example 2: Dotted keys don't need to be at the top level: */ Undotter::undot(['top' => ['a' => ['b.c' => 'FOO']]]); // => ['top' => ['a' => ['b' => ['c' => 'FOO']]]] /* Example 3: Conflict-Resolution depends on the order of elements in the input: */ Undotter::undot([ 'a' => ['b' => 'FOO'], 'a.b' => 'BAR' ]); // => ['a' => ['b' => 'BAR']] // ... but if the order is swapped Undotter::undot([ 'a.b' => 'BAR', 'a' => ['b' => 'FOO'] ]); // => ['a' => ['b' => 'FOO']] /* Example 4: If the conflicting values are both arrays, they're merged (using the same logic as ConfigAggregator): */ Undotter::undot([ 'a' => ['b' => ['foo' => 1, 'bar' => 2, 'baz' => 3]], 'a.b' => ['baz' => 4, 'qux' => 5] ]); // => // [ // 'a' => [ // 'b' => [ // 'foo' => 1, // 'bar', => 2, // 'baz' => 4, // 'qux' => 5 // ] // ] // ]
与Laminas ConfigAggregator一起使用
Undotter
是可调用的,这使得它很容易与laminas-config-aggregator一起作为后处理器使用。这很方便,因为它允许你在ConfigAggregator写入其缓存之前取消点符号。
例如,请参阅testMergesSubArrays()测试方法。