dennobaby / pathfinder
简单的PHP库,用于检查和操作数组
0.1.0
2021-11-09 11:25 UTC
Requires
- php: ^7.3
Requires (Dev)
- phpunit/phpunit: ^9.5
README
pathfinder
使用路径描述符访问和修改数组或JSON文档。
用法和示例
假设您有一个这个数组,它可能更大,您不知道某些路径是否存在
<?php
use Denno\PathFinder\PathFinder;
$array = [
'some' => [
'multi' => [
'dimensional' => [
'array' => 'foo',
],
],
],
];
检查给定路径是否存在
echo PathFinder::getPathValue($array, 'some.multi.dimensional.array');
echo PathFinder::getPathValue($array, 'some.multi.nonexisting.key');
会返回
true
false
如果您想修改给定路径的值,您可以这样做
echo PathFinder::setPathValue($array, 'some.multi.dimensional.array', 'bar');
//would return 'bar'
//let's check it:
echo PathFinder::getPathValue($array, 'some.multi.dimensional.array');
//would return true.
//but a nonexisting path?
echo PathFinder::setPathValue($array, 'some.multi.nonexisting.key', 'foobar');
//would return false, because the path don't exist!
//but you want it to be created and the value set? No problem:
echo PathFinder::setPathValue($array, 'some.multi.nonexisting.key', 'foobar', true);
//the last parameter, named 'force', will create it for you if set to true and therefor return 'foobar'