获取浮点值数组

时间:2018-11-29 14:44:01

标签: php wordpress

如何获取数组中字符串的浮点值?我在发票中需要它。

foreach( $this->get_woocommerce_totals() as $key => $total ) :

        if($total['label']==="Subtotal") $subtotal = $total['value'];

endforeach;

print_r($ total);

Array ( [label] => Subtotal [value] => 8.144 lei )

我已经尝试过了,但是没有帮助

$subtotal = (float)$total['value']; 
$subtotal = floatval($total['value']);

2 个答案:

答案 0 :(得分:1)

这是一种方法。请查看评论以获取逐步说明。

<?php

// $total['value']
$value = '8.144 lei';

// Regex explanation:
// ^ -- Start at beginning of input
// ( -- Start capture
// [\d\.] -- Allow all digits and/or a period.
// + -- Need one or more of character set.
// ) -- End capture

// preg_match() accepts in its third argument an array that will
// hold all matches made. The value you're after will be stored
// at index 1.
if (preg_match('/^([\d\.]+)/', $value, $matches) === 1)
    // Explicitly cast the captured string to a float.
    $floatVal = (float)$matches[1];
else
    die('Bad regex or no match made.');

// Outputs: float(8.144)
var_dump($floatVal);

答案 1 :(得分:0)

(float)floatval()都应该起作用。如果由于某些原因而没有这样做,那么比regexp更简单的解决方案是使用这种衬垫:

$price = '8.144 lei';
echo floatval(explode(' ', $price)[0]);

最好使用regexp,因为它也可以与8.1448.144 abc def more spaces甚至是空字符串(返回0)一起使用。

但是,这是一件微不足道的事情,您可以期望它成为WooCommerce的一部分-可能还有另一个函数可以返回所需的值。

根据文档,确实有满足每种需求的特定功能:

WC_Cart::get_cart_contents_total() – Gets cart total. This is the total of items in the cart, but after discounts. Subtotal is before discounts.
WC_Cart::get_shipping_total() – Get shipping_total.
WC_Cart::get_cart_subtotal(); - Gets the sub total (after calculation). **-> string, formatted price - not what you want**
WC_Cart::get_subtotal_tax() – Get subtotal.
WC_Cart::get_subtotal() – Get subtotal. **-> float, you are looking for that?**
WC_Cart::get_taxes_total() – Get tax row amounts with or without compound taxes includes.
wc_price() – Format the price with a currency symbol.

不幸的是,文档尚不清楚其中哪些文档考虑了税收,因此您需要尝试进行检查。至少从逻辑角度来看,get_subtotal()应该是您的事情。

相关问题