simplemehanizm / array
数组操作的实用函数集合
1.0
2023-12-13 16:15 UTC
Requires (Dev)
- phpunit/phpunit: ^10.4
README
该项目目前公开了两个函数,以帮助使用点表示法访问数组值
示例
在PHP中访问多维数组值可能会很麻烦,许多流行的语言都公开了所谓的“点表示法”,用于指定要访问的数组键/维度。
$array = [ 'this' => [ 'is' => [ 'deeply' => ['nested' => 'hello world'] ] ] ]; $value = $array['this']['is']['deeply']['nested']; // "hello world"
在上面的示例中,我们可能会尝试访问一个不存在的数组键,从而触发警告。使用点表示法和函数 arrayValue
,我们可以尝试访问值并避免触发错误。
use function SimpleMehanizm\Array\Functions\readValue; $array = [ 'this' => [ 'is' => [ 'deeply' => ['nested' => 'hello world'] ] ] ]; $path = 'this.is.deeply.nested'; $value = readValue($array, $path); // "hello world"
为什么你会使用点表示法
在将值保存到数据库或其他持久化层的情况下,其中描述了特定值在配置数组中的位置,将点表示法保存到值中,然后使用 readValue
函数访问它是有用的。