ecfectus / dotable
一个简单的点表示法访问数组类和特性。
dev-master
2016-10-08 00:26 UTC
Requires
- php: >=7.0.0
Requires (Dev)
- phpdocumentor/phpdocumentor: 2.*
- phpunit/phpunit: ^5.5.0
This package is not auto-updated.
Last update: 2024-09-18 19:36:53 UTC
README
一个简单的点表示法访问数组类和特性,实现了 DotableInterface, ArrayAccess, IteratorAggregate, Countable, JsonSerializable。
此类可以将普通数组转换为具有点表示法的超级数组,您可以使用辅助方法 set
、get
、has
、forget
、prepend
、append
、merge
和 count
来修改底层数组。或者您也可以像访问任何其他数组一样访问它,使用 foreach
、isset
、unset
、count
和 `$array['dot.notation.key']`。
用法
$d = new Dotable([]); //these are both the same. $d['one'] = ['two' => ['three' => 1], 'four' => ['val']]; === $d->set('one', ['two' => ['three' => 1], 'four' => ['val']); //and these $var = $d['one.two.three']; === $var = $d->get('one.two.three', 1);//optional default value //and these $d['one.two.three'] = 2; === $d->set('one.two.three', 2); //existence is the same isset($d['one.two.three']);//true isset($d['one.two.five']);//false === $d->has('one.two.three');//true $d->has('one.two.five');//false //and removal unset($d['one.two.three']); === $d->forget('one.two.three'); //prepend $v = $d['one.four']; array_unshift($v, 'val2'); $d['one.four'] = $v === $d->prepend('one.four', 'val2'); //append $v = $d['one.four']; $v[] = 'val2'; $d['one.four'] = $v === $d->append('one.four', 'val2'); //merge // merging is a little different, array_merge_recursive has some weird side effects for multi dimensional arrays with different value types, // by default we use the dotable merge stratergy which overcomes this with distinct values, // but if your expecting exactly what array_merge_recursive does, simply pass false as the third argument. $res = array_merge_recursive($d['one'], ['two' => ['three' => 2]); === $d->merge('one', ['two' => ['three' => 2], true|false); //count count($d); === $d->count(); //get a plain array $d->toArray(); //loop over the array foreach($d as $key => $value){} === foreach($d->toArray() as $key => $value){}
使用特性
dotable 类简单地使用提供的特性并实现所有接口:DotableInterface、ArrayAccess、IteratorAggregate、Countable、JsonSerializable。
您可以在不扩展 Dotable 类的不同类中使用全部功能。
class MyClass extends Dotable implements DotableInterface, ArrayAccess, IteratorAggregate, Countable, JsonSerializable {} //or class MyClass implements DotableInterface, ArrayAccess, IteratorAggregate, Countable, JsonSerializable { use DotableTrait; public function __construct(array $items = []) { $this->set('', $items);//set the items using the traits method on the root index. } }
现在 MyClass
具有dotable的所有功能,无需扩展它。请注意,如果您在类中提供了与特性方法(包括实现接口的方法)冲突的同名方法,您将丢失功能。为确保其维护,您需要像在 php 文档中解释的那样重写方法签名:https://php.ac.cn/manual/en/language.oop5.traits.php #example 6。