madesimple / php-arrays
操作数组帮助函数
v3.0.0
2024-08-19 08:01 UTC
Requires
- php: >=7.4
- ext-json: *
Requires (Dev)
- phpunit/phpunit: ^9.5
README
操作数组帮助函数。
Arr & ArrDots
Arr
和 ArrDots
包含一组针对数组的静态帮助方法。这些方法可以用于 array
和 \ArrayAccess
对象。有关更多信息,请参阅类内的 PHPDocs。
点操作符
Dots
是一个实现 \ArrayAccess
的实例,它使用来自 \MadeSimple\ArrDots
的函数。可以将 Dots
实例作为 array
传递给 ArrDots
。
创建 Dots
有三种方式
// Create an empty dot array $dots = new \MadeSimple\Dots(); // Create a dot array with a pre-existing array $dots = new \MadeSimple\Dots($array); // Create a dot array with $dots = new \MadeSimple\Dots([ 'address' => [ 'houseNo' => '123', 'street' => 'Fake St', 'postCode' => 'AB12 3CD', ], 'comments' => [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'Donec nec pellentesque est.', 'Quisque volutpat quam et est laoreet, vitae consectetur erat molestie.', ] ]);
一旦创建 Dots
,您可以按以下方式替换以下下划线数组
// Set an array after dot array // Changes will _not_ be reflected in the original array $dots->setArray($array); // Set an array as a reference // Changes will be reflected in the original array $dots->setReference($array);
Dots
的基本用法
// Get a value using dot notation: echo "Post Code: ", $dots['address.postCode'], PHP_EOL; // Set a value using dot notation: $dots['address.postCode'] = 'EF45 6GH'; echo "Post Code: ", $dots['address.postCode'], PHP_EOL; // Remove a value using dot notation: unset($dots['address.postCode']); echo "Exists: ", (isset($dots['address.postCode']) ? 'yes' : 'no'), PHP_EOL; // Add a value using dot notation: $dots['address.postCode'] = 'IJ78 9KL'; echo "Post Code: ", $dots['address.postCode'], PHP_EOL; // Access nth element in an sub array echo "Comment: ", $dots['comments.1'], PHP_EOL;