byjoby / flatrr
一个通过扁平化键操作多维数组的库
v1.5.1
2024-03-07 18:42 UTC
Requires
- php: >=8.1
- symfony/yaml: ^6.4
Requires (Dev)
- phpstan/phpstan: ^1.9
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.7
README
Flatrr 能做什么
Flatrr 是一个用于通过扁平化键名访问数组的实用库。例如,您可以使用 $arr['foo.bar']
而不是 $arr['foo']['bar']
。如果想要通过字符串构建来设置将用于访问数组的键,这通常很有用。
需要注意的是,由于数组和引用的工作方式,这并不总是在所有情况下都与原生数组完全相同。实际上存在无数小的限制,因此通常应该按照文档说明使用此库。由于此工具的特性,使用未经记录的功能非常不可预测,并且未来在底层可能会有显著不同的工作方式。
FlatArray
主 FlatArray 类非常简单。它仅实现了 \Array 和 \Iterator。利用它可以创建数组,将值合并到其中,并通过扁平化键检索数组的一部分。
构建和获取值
// Instantiating FlatArrays can be done by passing them an array // Keys in the initial array will be unflattened, for example the following // yields a FlatArray containing ['foo'=>'bar','bar'=>['baz'=>'a','buz'=>'u']] $f = new \Flatrr\FlatArray([ 'foo' => 'bar', 'bar.baz' => 'a', 'bar.buz' => 'u' ]);
您可以通过 get()
方法或通过扁平化键像访问普通数组一样访问数组中的值。
// All of the following are equal to 'a' $f['bar']['baz']; $f['bar.baz']; $f->get('bar.baz');
设置值
值可以通过扁平化键或 set()
方法设置。像普通的多维数组一样设置值只会影响第一层,并且不应该这样做。
// Both of these work $f['foo.bar'] = 'baz'; $f->set('foo.bar','baz'); // This does NOT work $f['foo']['bar'] = 'baz';
SelfReferencingFlatArray
SelfReferencingFlatArray 是一个类,它执行 FlatArray 所做的所有操作,但还允许数组内的字符串引用数组内的其他字段,并将它们作为字符串包含进来。例如
$f = new \Flatrr\SelfReferencingFlatArray([ 'foo.bar' => 'baz', 'foo.baz' => '${foo.bar}' ]); // foo.baz will now always return the value of foo.bar // echoes 'baz' echo $f['foo.baz']; // You can also get the "raw" value of a field using get() // echoes '${foo.bar}' echo $f->get('foo.baz'); // Variables can also be used as part of other strings $f['a'] = 'foo.bar is: ${foo.bar}'; // echoes 'foo.bar is: baz' echo $f['a']; // Variables are resolved recursively $f['b'] = 'foo.baz is: ${foo.baz}'; // echoes 'foo.baz is: baz' echo $f['b'];
配置
Config 与 SelfReferencingFlatArray 执行相同的功能,但增加了读取 INI、JSON 和 YAML 文件的方法。它还提供了将内容提取为 JSON 和 YAML 的方法。