首页 > 解决方案 > PHP 分隔字符串

问题描述

我有一个包含128.82. 我想将它们拆分/分隔为100and 28.82

var_dump(substr($kwh,0,3));
        die();

它给了我128

我怎样才能分开100and 28.82

任何帮助将不胜感激

注意:我设置这个是因为我已经定义了slabs。1-100, 101-150, 等等。所以我需要根据平板设置它们。板可能会有所不同,因为它可能是1-5051-100100-150等等。所以我必须128.8250for 1-5050for51-100然后28.82for那样划分/拆分101-150

标签: phpstringsplityii2

解决方案


$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

推荐阅读