さまざまな量の配列を取り、小数点以下の桁数を揃える関数を作成しようとしました。これは、
長さが最も長い数値よりも短い長さの各数値に適切な量を追加することによって行われます。
かなり長いようですが、どうすればもっと短く効率的にできるかについて誰かが洞察を持っているのではないかと思います.
$arr = array(12, 34.233, .23, 44, 24334, 234);
function align_decimal ($arr) {
$long = 0;
$len = 0;
foreach ( $arr as &$i ){
//change array elements to string
(string)$i;
//if there is no decimal, add '.00'
//if there is a decimal, add '00'
//ensures that there are always at least two zeros after the decimal
if ( strrpos( $i, "." ) === false ) {
$i .= ".00";
} else {
$i .= "00";
}
//find the decimal
$dec = strrpos( $i, "." );
//ensure there are only two decimals
//$dec+3 is the decimal plus two characters
$i = substr_replace($i, "", $dec+3);
//if $i is longer than $long, set $long to $i
if ( strlen($i) >= strlen($long) ) {
$long = $i;
}
}
//locate the decimal in the longest string
$long_dec = strrpos( $long, "." );
foreach ( $arr as &$i ) {
//difference between $i and $long position of the decimal
$z = ( $long_dec - strrpos( $i, "." ) );
$c = 0;
while ( $c <= $z ) {
//add a for each number of characters
//between the two decimal locations
$i = " " . $i;
$c++;
}
}
return $arr;
}
それはうまくいきます...本当に冗長に思えます。より短く、よりプロフェッショナルにする方法は無数にあると確信しています。アイデアをありがとう!