saasformation / array-by-path
使用点路径在数组中获取/设置值的库
1.0.0
2022-04-06 17:11 UTC
Requires (Dev)
- phpunit/phpunit: ^9.5
README
ArrayByPath 是一个使用点路径在数组中获取/设置的库
安装
使用 composer 需求此库
composer require saasformation/array-by-path
入门指南
让我们假设你有一个以下数组
$array = [ 'data' => [ 'id' => '53b3ed90-b5ae-11ec-b909-0242ac120002', 'attributes' => [ 'name' => 'John', 'surname' => 'Smith', 'birthdate' => '1990-01-20', 'savings_total_amount' => [ 'amount' => 2045033, 'currency' => 'EUR' ] ] ] ];
使用 ArrayByPath,你可以使用这样的路径获取值
$name = (new RetrieveArrayValueByPathService())->find('data.attributes.name', $array); // "John"
find 总是返回一个值或 null,如果路径不存在。
$invalidPath = (new RetrieveArrayValueByPathService())->find('foo', $array); // null
如果你想当路径不存在时抛出异常,那么使用 get
$invalidPath = (new RetrieveArrayValueByPathService())->get('foo', $array); // InvalidPathException
此外,你可以使用路径在数组中设置新的值,如下所示
(new SetValueToArrayByPathService())->insert('data.attributes.height', $array, 177);
如果路径已经有一个值,则将抛出 PathAlreadyExistsException
。如果你在这种情况下希望更新值,请使用 upsert
。
问题
如果你在库中遇到问题,请在这里的 GitHub 上自由地打开一个问题。