每次我尝试运行此代码时都会显示一条消息:
Fatal error: Call to undefined function money_format()
存在该问题的行是:
$pricetotal = money_format("%10.2n", $pricetotal);
和
$cartTotal = money_format("%10.2n", $cartTotal);
你能解释一下这种情况发生的原因吗?
$cartOutput = "";
$cartTotal = "";
$pp_checkout_btn = '';
$product_id_array = '';
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
$cartOutput = "<h2 align='center'>Your shopping cart is empty</h2>";
} else {
// Start PayPal Checkout Button
$pp_checkout_btn .= '<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="you@youremail.com">';
// Start the For Each loop
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item) {
$item_id = $each_item['item_id'];
$sql = mysql_query("SELECT * FROM products WHERE id='$item_id' LIMIT 1");
while ($row = mysql_fetch_array($sql)) {
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
}
$pricetotal = $price * $each_item['quantity'];
$cartTotal = $pricetotal + $cartTotal;
setlocale(LC_MONETARY, "en_US");
$pricetotal = money_format("%10.2n", $pricetotal);
// Dynamic Checkout Btn Assembly
$x = $i + 1;
$pp_checkout_btn .= '<input type="hidden" name="item_name_' . $x . '" value="' . $product_name . '">
<input type="hidden" name="amount_' . $x . '" value="' . $price . '">
<input type="hidden" name="quantity_' . $x . '" value="' . $each_item['quantity'] . '"> ';
// Create the product array variable
$product_id_array .= "$item_id-".$each_item['quantity'].",";
// Dynamic table row assembly
$cartOutput .= "<tr>";
$cartOutput .= '<td><a href="product.php?id=' . $item_id . '">' . $product_name . '</a><br /><img src="inventory_images/' . $item_id . '.jpg" alt="' . $product_name. '" width="40" height="52" border="1" /></td>';
$cartOutput .= '<td>' . $details . '</td>';
$cartOutput .= '<td>$' . $price . '</td>';
$cartOutput .= '<td><form action="cart.php" method="post">
<input name="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" />
<input name="adjustBtn' . $item_id . '" type="submit" value="change" />
<input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
</form></td>';
//$cartOutput .= '<td>' . $each_item['quantity'] . '</td>';
$cartOutput .= '<td>' . $pricetotal . '</td>';
$cartOutput .= '<td><form action="cart.php" method="post"><input name="deleteBtn' . $item_id . '" type="submit" value="X" /><input name="index_to_remove" type="hidden" value="' . $i . '" /></form></td>';
$cartOutput .= '</tr>';
$i++;
}
setlocale(LC_MONETARY, "en_US");
$cartTotal = money_format("%10.2n", $cartTotal);
$cartTotal = "<div style='font-size:18px; margin-top:12px;' align='right'>Cart Total : ".$cartTotal." USD</div>";
// Finish the Paypal Checkout Btn
$pp_checkout_btn .= '<input type="hidden" name="custom" value="' . $product_id_array . '">
<input type="hidden" name="notify_url" value="https://www.yoursite.com/storescripts/my_ipn.php">
<input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="cbt" value="Return to The Store">
<input type="hidden" name="cancel_return" value="https://www.yoursite.com/paypal_cancel.php">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="currency_code" value="USD">
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but01.gif" name="submit" alt="Make payments with PayPal - its fast, free and secure!">
</form>';
}
?>
答案 0 :(得分:52)
如果您使用的是基于Windows的系统,那么您将无法使用此功能。
函数money_format()仅在系统具有strfmon功能时定义。例如,Windows没有,因此在Windows中未定义money_format()。
(Mike W在评论中也指出了这一点)
答案 1 :(得分:41)
有人指出,您可能没有此功能,因为它并非在所有操作系统上都存在(请参阅Mike W的评论或学习者学生的答案)。
由于系统中缺少该功能,您可以根据number_format function编写自己的功能。您似乎希望将该数字格式设置为美元,因此默认值(十进制= .
和千位= ,
应该适用于您)。
function asDollars($value) {
return '$' . number_format($value, 2);
}
然后你可以替换
$pricetotal = money_format("%10.2n", $pricetotal);
与
$pricetotal = asDollars($pricetotal);
答案 2 :(得分:1)
在Laravel上开发网站时,我遇到了同样的问题。 对我来说,我替换了旧代码:
return money_format('$%i', $this->price / 100);
具有以下内容:
return '$' . number_format(($this->price) / 100);
答案 3 :(得分:1)
对于Windows WAMP User and > PHP v7.4.2
,您可以使用此函数,该函数为此处的所有平台实现相同的函数money_format()
请使用该函数作为后备.. 所以使用 if ( ! function_exists( 'money_format' ) ) {}
以避免函数无法重新声明致命错误。
以下为快速复制...
if ( ! function_exists( 'money_format' ) ) {
function money_format($format, $number)
{
$regex = '/%((?:[\^!\-]|\+|\(|\=.)*)([0-9]+)?'.
'(?:#([0-9]+))?(?:\.([0-9]+))?([in%])/';
if (setlocale(LC_MONETARY, 0) == 'C') {
setlocale(LC_MONETARY, '');
}
$locale = localeconv();
preg_match_all($regex, $format, $matches, PREG_SET_ORDER);
foreach ($matches as $fmatch) {
$value = floatval($number);
$flags = array(
'fillchar' => preg_match('/\=(.)/', $fmatch[1], $match) ?
$match[1] : ' ',
'nogroup' => preg_match('/\^/', $fmatch[1]) > 0,
'usesignal' => preg_match('/\+|\(/', $fmatch[1], $match) ?
$match[0] : '+',
'nosimbol' => preg_match('/\!/', $fmatch[1]) > 0,
'isleft' => preg_match('/\-/', $fmatch[1]) > 0
);
$width = trim($fmatch[2]) ? (int)$fmatch[2] : 0;
$left = trim($fmatch[3]) ? (int)$fmatch[3] : 0;
$right = trim($fmatch[4]) ? (int)$fmatch[4] : $locale['int_frac_digits'];
$conversion = $fmatch[5];
$positive = true;
if ($value < 0) {
$positive = false;
$value *= -1;
}
$letter = $positive ? 'p' : 'n';
$prefix = $suffix = $cprefix = $csuffix = $signal = '';
$signal = $positive ? $locale['positive_sign'] : $locale['negative_sign'];
switch (true) {
case $locale["{$letter}_sign_posn"] == 1 && $flags['usesignal'] == '+':
$prefix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 2 && $flags['usesignal'] == '+':
$suffix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 3 && $flags['usesignal'] == '+':
$cprefix = $signal;
break;
case $locale["{$letter}_sign_posn"] == 4 && $flags['usesignal'] == '+':
$csuffix = $signal;
break;
case $flags['usesignal'] == '(':
case $locale["{$letter}_sign_posn"] == 0:
$prefix = '(';
$suffix = ')';
break;
}
if (!$flags['nosimbol']) {
$currency = $cprefix .
($conversion == 'i' ? $locale['int_curr_symbol'] : $locale['currency_symbol']) .
$csuffix;
} else {
$currency = '';
}
$space = $locale["{$letter}_sep_by_space"] ? ' ' : '';
$value = number_format($value, $right, $locale['mon_decimal_point'],
$flags['nogroup'] ? '' : $locale['mon_thousands_sep']);
$value = @explode($locale['mon_decimal_point'], $value);
$n = strlen($prefix) + strlen($currency) + strlen($value[0]);
if ($left > 0 && $left > $n) {
$value[0] = str_repeat($flags['fillchar'], $left - $n) . $value[0];
}
$value = implode($locale['mon_decimal_point'], $value);
if ($locale["{$letter}_cs_precedes"]) {
$value = $prefix . $currency . $space . $value . $suffix;
} else {
$value = $prefix . $value . $space . $currency . $suffix;
}
if ($width > 0) {
$value = str_pad($value, $width, $flags['fillchar'], $flags['isleft'] ?
STR_PAD_RIGHT : STR_PAD_LEFT);
}
$format = str_replace($fmatch[0], $value, $format);
}
return $format;
}
}
答案 4 :(得分:-1)
function money_format($formato, $valor) {
if (setlocale(LC_MONETARY, 0) == 'C') {
return number_format($valor, 2);
}
$locale = localeconv();
$regex = '/^'. // Inicio da Expressao
'%'. // Caractere %
'(?:'. // Inicio das Flags opcionais
'\=([\w\040])'. // Flag =f
'|'.
'([\^])'. // Flag ^
'|'.
'(\+|\()'. // Flag + ou (
'|'.
'(!)'. // Flag !
'|'.
'(-)'. // Flag -
')*'. // Fim das flags opcionais
'(?:([\d]+)?)'. // W Largura de campos
'(?:#([\d]+))?'. // #n Precisao esquerda
'(?:\.([\d]+))?'. // .p Precisao direita
'([in%])'. // Caractere de conversao
'$/'; // Fim da Expressao
if (!preg_match($regex, $formato, $matches)) {
trigger_error('Formato invalido: '.$formato, E_USER_WARNING);
return $valor;
}
$opcoes = array(
'preenchimento' => ($matches[1] !== '') ? $matches[1] : ' ',
'nao_agrupar' => ($matches[2] == '^'),
'usar_sinal' => ($matches[3] == '+'),
'usar_parenteses' => ($matches[3] == '('),
'ignorar_simbolo' => ($matches[4] == '!'),
'alinhamento_esq' => ($matches[5] == '-'),
'largura_campo' => ($matches[6] !== '') ? (int)$matches[6] : 0,
'precisao_esq' => ($matches[7] !== '') ? (int)$matches[7] : false,
'precisao_dir' => ($matches[8] !== '') ? (int)$matches[8] : $locale['int_frac_digits'],
'conversao' => $matches[9]
);
if ($opcoes['usar_sinal'] && $locale['n_sign_posn'] == 0) {
$locale['n_sign_posn'] = 1;
} elseif ($opcoes['usar_parenteses']) {
$locale['n_sign_posn'] = 0;
}
if ($opcoes['precisao_dir']) {
$locale['frac_digits'] = $opcoes['precisao_dir'];
}
if ($opcoes['nao_agrupar']) {
$locale['mon_thousands_sep'] = '';
}
$tipo_sinal = $valor >= 0 ? 'p' : 'n';
if ($opcoes['ignorar_simbolo']) {
$simbolo = '';
} else {
$simbolo = $opcoes['conversao'] == 'n' ? $locale['currency_symbol']
: $locale['int_curr_symbol'];
}
$numero = number_format(abs($valor), $locale['frac_digits'], $locale['mon_decimal_point'], $locale['mon_thousands_sep']);
$sinal = $valor >= 0 ? $locale['positive_sign'] : $locale['negative_sign'];
$simbolo_antes = $locale[$tipo_sinal.'_cs_precedes'];
$espaco1 = $locale[$tipo_sinal.'_sep_by_space'] == 1 ? ' ' : '';
$espaco2 = $locale[$tipo_sinal.'_sep_by_space'] == 2 ? ' ' : '';
$formatado = '';
switch ($locale[$tipo_sinal.'_sign_posn']) {
case 0:
if ($simbolo_antes) {
$formatado = '('.$simbolo.$espaco1.$numero.')';
} else {
$formatado = '('.$numero.$espaco1.$simbolo.')';
}
break;
case 1:
if ($simbolo_antes) {
$formatado = $sinal.$espaco2.$simbolo.$espaco1.$numero;
} else {
$formatado = $sinal.$numero.$espaco1.$simbolo;
}
break;
case 2:
if ($simbolo_antes) {
$formatado = $simbolo.$espaco1.$numero.$sinal;
} else {
$formatado = $numero.$espaco1.$simbolo.$espaco2.$sinal;
}
break;
case 3:
if ($simbolo_antes) {
$formatado = $sinal.$espaco2.$simbolo.$espaco1.$numero;
} else {
$formatado = $numero.$espaco1.$sinal.$espaco2.$simbolo;
}
break;
case 4:
if ($simbolo_antes) {
$formatado = $simbolo.$espaco2.$sinal.$espaco1.$numero;
} else {
$formatado = $numero.$espaco1.$simbolo.$espaco2.$sinal;
}
break;
}
if ($opcoes['largura_campo'] > 0 && strlen($formatado) < $opcoes['largura_campo']) {
$alinhamento = $opcoes['alinhamento_esq'] ? STR_PAD_RIGHT : STR_PAD_LEFT;
$formatado = str_pad($formatado, $opcoes['largura_campo'], $opcoes['preenchimento'], $alinhamento);
}
return $formatado;
}