我有一个小数 (5,2),我试图将其分成一个数组。
所以如果数字是..
123.45 = array([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
23.45 = array([0] => 0 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
3.45 = array([0] => 0 [1] => 0 [2] => 3 [3] => 4 [4] => 5 )
我有一个相当大的代码来做到这一点,我想知道是否有人有更简单的方法将每个数字放入这个数组中,因为我觉得我的代码非常复杂。
$number = 123.35;
$number_array = explode(".", $number);
$final_array = array(0);
if(!empty(@(string)$number_array[0][0]) && !empty(@(string)$number_array[0][1]) && !empty(@(string)$number_array[0][2]))
{
$final_array[0] = @(string)$number_array[0][0];
$final_array[1] = @(string)$number_array[0][1];
$final_array[2] = @(string)$number_array[0][2];
}
elseif(!empty(@(string)$number_array[0][0]) && !empty(@(string)$number_array[0][1]) && empty(@(string)$number_array[0][2]))
{
$final_array[0] = 0;
$final_array[1] = @(string)$number_array[0][0];
$final_array[2] = @(string)$number_array[0][1];
}
elseif(!empty(@(string)$number_array[0][0]) && empty(@(string)$number_array[0][1]) && empty(@(string)$number_array[0][2]))
{
$final_array[0] = 0;
$final_array[1] = 0;
$final_array[2] = @(string)$number_array[0][0];
}
else
{
$final_array[0] = 0;
$final_array[1] = 0;
$final_array[2] = 0;
}
empty(@(string)$number_array[1][0]) ? $final_array[3] = 0 : $final_array[3] = @(string)$number_array[1][0];
empty(@(string)$number_array[1][1]) ? $final_array[4] = 0 : $final_array[4] = @(string)$number_array[1][1];
$number = str_replace('.', '', (string) 13.35);
$number = str_pad($number, 5, "0", STR_PAD_LEFT);
var_dump(str_split($number));
我认为这就是您正在寻找的:
list($whole, $decimal) = sscanf($number, '%d.%d');
$result = str_split(sprintf('%03s',$whole) . $decimal);
测试用例:
foreach ([123.45, 23.45, 3.45] as $number) {
list($whole, $decimal) = sscanf($number, '%d.%d');
$result = str_split(sprintf('%03s',$whole).$decimal);
echo implode(', ', $result) . "\n";
}
输出:
1, 2, 3, 4, 5
0, 2, 3, 4, 5
0, 0, 3, 4, 5
我将演示如何解析来自 MYSQL 查询的 DECIMAL(5,2) 列值。 该列(在我的脚本中名为
float
)将作为字符串返回,一致填充到小数点后两位。
这意味着您可以拆分字符串然后填充数组或填充字符串然后拆分为数组。
我的测试数据库数据如下所示:
浮点数 -- DECIMAL(5,2) |
---|
123.45 |
23.45 |
3.45 |
3.40 |
0.40 |
代码:(PHPize演示)
foreach ($conn->query('SELECT * FROM decimals') as ['float' => $f]) {
echo json_encode(
array_pad(preg_split('/\B|\./', $f), -5, '0')
) . "\n";
}
输出:
["1","2","3","4","5"]
["0","2","3","4","5"]
["0","0","3","4","5"]
["0","0","3","4","0"]
["0","0","0","4","0"]
如果您想将每个数字转换为整数值(而不是字符串),那么
sscanf()
提供了一种直接方法。
代码:([PHPize 演示)
foreach ($mysqli->query('SELECT * FROM decimals') as ['float' => $f]) {
echo json_encode(
sscanf(str_pad($f, 6, '0', STR_PAD_LEFT), '%1d%1d%1d.%1d%1d')
) . "\n";
}
输出:
[1,2,3,4,5]
[0,2,3,4,5]
[0,0,3,4,5]
[0,0,3,4,0]
[0,0,0,4,0]