php - PHP 分隔字符串
问题描述
我有一个包含128.82
. 我想将它们拆分/分隔为100
and 28.82
。
var_dump(substr($kwh,0,3));
die();
它给了我128
。
我怎样才能分开100
and 28.82
?
任何帮助将不胜感激
注意:我设置这个是因为我已经定义了slabs。1-100
, 101-150
, 等等。所以我需要根据平板设置它们。板可能会有所不同,因为它可能是1-50
、51-100
、100-150
等等。所以我必须128.82
像50
for 1-50
,50
for51-100
然后28.82
for那样划分/拆分101-150
解决方案
$input = '128.82'; // we’re doing math here, so actually we’ll be working with numbers,
// but PHP will automatically cast here
$slabs = [50, 100, 150, 200];
$result = [];
$previous_slab = 0;
foreach($slabs as $slab) {
// calculate distance between current and previous slab
$slab_distance = $slab - $previous_slab;
// if current remainder of input value is >= distance, add distance to result,
// and subtract distance from remainder of input
if( $input >= $slab_distance ) {
$result[] = $slab_distance;
$input -= $slab_distance;
}
// otherwise, add remainder as last item of result, and break out of the loop here
else {
$result[] = $input;
break;
}
$previous_slab = $slab;
}
var_dump($result);
给定板的结果:
array (size=3)
0 => int 50
1 => int 50
2 => float 28.82
[50, 75, 150, 200] 的结果:
array (size=3)
0 => int 50
1 => int 25
2 => float 53.82
推荐阅读
- python - 带有数组的 Python Sklearn 管道
- react-native - Animated.View 和 Animated.Value 抛出只读赋值或不可变对象错误
- google-cloud-platform - AWS 使用私钥承担 iam 角色与 gcp 的 json 文件
- entity-framework - Linq To Entities - 在 DB 上运行 CONVERT to int
- macos - NSTableView 内的 NSTableViewCell
- apache-spark - 在使用带有 kafka 的火花流时,无法迭代从将 Dstream 转换为 List 中检索到的键列表
- angular - 角度形式:无法读取未定义的属性“cafPlanForm”
- java - 在java中模拟ExecutorService的invokeAll方法
- android - 是否可以使用简单的浏览器从我的网站安装 Android 应用程序?
- python-3.x - 不能 Glob 几种文件类型