软盒实验室 / php-array-utils
包含多个数组实用程序的库。
v0.0.7
2017-06-18 21:58 UTC
Requires (Dev)
- phpunit/phpunit: 5.5.*
This package is not auto-updated.
Last update: 2024-09-29 00:42:14 UTC
README
帮助将数组数组的值进行类型转换。当需要保证输出值的类型时使用,例如,将数组编码为JSON。除了转换值之外,还可以进行格式化。
安装
composer require tarcisiojr/php-cast
使用
示例
class Example { public function test() { $value = [ "a" => [ "b" => [ "c1" => "a", "c2" => "2", "c3" => "3", "c4" => ["1", "2", "3"], "c5" => [ ["d1" => "9"], ["d1" => "8"], ["d1" => "7"], ] ] ] ]; // 1. Create a instance of CastHelper // 2. Configure the rules to cast values // 3. Execute method 'cast' to cast array values $ret = (new CastHelper()) ->addRule("a.b.c1", "string") ->addRule("a.b.c2", "int") ->addRule("a.b.c3", "float") ->addRule("a.b.c4.*", "int") ->addRule("a.b.c5.*.d1", "string|lpad:2,0") ->cast($value); echo "\n\n" . json_encode($ret, JSON_PRETTY_PRINT); } }
输出
{
"a": {
"b": {
"c1": "a",
"c2": 2,
"c3": 3,
"c4": [
1,
2,
3
],
"c5": [
{
"d1": "09"
},
{
"d1": "08"
},
{
"d1": "07"
}
]
}
}
}
路径表达式
- a.b 选择 "value"
[
"a" => [
"b" => "value"
]
];
- a.2.b 选择 "two"
[
"a" => [
[ "b" => "zero" ],
[ "b" => "one" ],
[ "b" => "two" ],
[ "b" => "three" ]
]
];
- a.*.b 选择所有值 "zero", "one", "two" 和 "three"
[
"a" => [
[ "b" => "zero" ],
[ "b" => "one" ],
[ "b" => "two" ],
[ "b" => "three" ]
]
];
规则表达式
表达式: cast_type|option_1:param_1,param_2,...param_n;option_2:param_1...;option_n...
其中 cast_type 是转换规则的标识符,选项是针对值执行的其他配置,例如,trim,pad 等。
转换类型
- int: 转换为 int 值。
- float: 转换为浮点值。
- bool: 转换为布尔值。
- string: 转换为字符串值。
- max_length:size 截断值到最大长度。
- rpad:size,char 在右侧用提供的字符填充。
- lpad:size,char 在左侧用提供的字符填充。
扩展
可以添加新的转换规则,为此需要创建一个扩展 CastRule 接口的类,并使用 PHP\Cast\CastRule\CastRuleFactory::registerCastRule 方法进行注册。可以使用 PHP\Cast\CastRule\CastRuleBase 来缩短路径。请参见上面的示例
class BooleanCastRule extends PHP\Cast\CastRule\CastRuleBase { public function getIdentifier() { return "bool"; } public function cast($value) { return (boolean) $value; } } ... PHP\Cast\CastRule\CastRuleFactory::registerCastRule(new BooleanCastRule()); ...