PHP中的自定义函数在某些情况下不起作用。
代码:
<?php
function short_format_indian_c($n) {
$precision = 3;
$n_format = number_format($n / 1000, $precision);
$n_format = number_format($n_format, 2);
$n_format = $n_format + 0;
$n_format = $n_format . ' K';
return $n_format;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
var checkState = function(){
var tq = jQuery('#tq');
tq.html(18000);
}
checkState();
setInterval(checkState, 1000);
</script>
<?php $tq = '<span id="tq"></span>';?><?php echo short_format_indian_c($tq); ?>
如果我使用 echo short_format_indian_c(1800),它会将结果显示为 18 K 。
但是当我使用 echo short_format_indian_c($ tq)时,它会将结果显示为 0 K ,其中 $ tq 也是 18000
答案 0 :(得分:0)
好吧,你的函数需要一个参数。当你在代码中调用它时
<?php echo short_format_indian_c($tq); ?>
您传递$ tq作为参数。 $ tq目前等于“”
<?php $tq = '<span id="tq"></span>';?>
在函数内部,您对参数执行除法,在本例中是一个字符串。由于该过程,字符串将被转换为int并且将等于0.因此,您将得到0 K.
另一方面,当您传递18000作为参数时,一切都会按预期工作。
答案 1 :(得分:0)
<?php
echo short_format_indian_c($tq); // There $tq not have any number only value thats why this not give a proper output.
?>
<?php
//This code run only server side.
function short_format_indian_c($n) {
$precision = 3;
$n_format = number_format($n / 1000, $precision);
$n_format = number_format($n_format, 2);
$n_format = $n_format + 0;
$n_format = $n_format . ' K';
return $n_format;
}
// As per User need.
function kFormatter($num) {
// return ($num > 999) ?(round(($num/1000),2).'K':$num; //Not return K for less than 1000 ;
return round(($num/1000),2).'K'; // work for all numbers
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
//This part only run at client side.
function kFormatter(num) {
// return num > 999 ? (num/1000).toFixed(1) + 'K' : num; //Not return K for less than 1000 ;
return (num/1000).toFixed(1) + 'K'; // work for all numbers
}
// Function for all format indian Currency.
function short_format_indian_c(num) {
if(num < 1000)
{
return num; // For Less then 1000
}
else if(num >= 1000 && num < 99999)
{
return (num/1000).toFixed(1) + 'K'; // for 1000 multiplier till 99999
}
else if(num >= 100000 && num < 9999999)
{
return (num/100000).toFixed(1) + 'L'; // for 100000 multiplier till 9999999
}
else if(num >= 10000000 && num < 999999999)
{
return (num/10000000).toFixed(1) + 'C'; // for 10000000 multiplier till 999999999
}
else
{
return num; // For all other num instead
}
}
var checkState = function(){
var tq = jQuery('#tq');
tq.html(short_format_indian_c(18000));
// This will provide an output as 18K in element have id is tq;
}
checkState();
setInterval(checkState, 1000);
</script>
<?php
$tq = '<span id="tq"></span>'; // Wrong way to assign html value in a php variable.
$tq = '18000'; // this will work instead.
?>
<?php
echo short_format_indian_c($tq); // There $tq not have any number only value thats why this not give a proper output.
?>
注意!如果您在客户端需要结果,那么您还需要为javascript编写此函数; Fiddle