循环遍历多维数组并将值转换为float

时间:2015-01-20 22:54:22

标签: php multidimensional-array casting

我有以下多维数组。请注意,payment_amount,payment_interest和payment_principle是字符串。我需要将这些值转换为浮点数。我得到了所有的扭曲,有人可以建议一个foreach()来完成这个吗?

array (size=12)
  0 => 
    array (size=4)
      'payment_date' => string '2015-01-01' (length=10)
      'payment_amount' => string '159609.00' (length=9)
      'payment_interest' => string '26697.78' (length=8)
      'payment_principle' => string '132911.22' (length=9)
  1 => 
    array (size=4)
      'payment_date' => string '2015-02-01' (length=10)
      'payment_amount' => string '159609.00' (length=9)
      'payment_interest' => string '25039.44' (length=8)
      'payment_principle' => string '134569.56' (length=9)
  2 => 
    array (size=4)
      'payment_date' => string '2015-03-01' (length=10)
      'payment_amount' => string '159609.00' (length=9)
      'payment_interest' => string '23356.20' (length=8)
      'payment_principle' => string '136252.80' (length=9)
  3 => 
    array (size=4)
      'payment_date' => string '2015-04-01' (length=10)
      'payment_amount' => string '159609.00' (length=9)
      'payment_interest' => string '21653.04' (length=8)
      'payment_principle' => string '137955.96' (length=9)
  4 => 
    array (size=4)
      'payment_date' => string '2015-05-01' (length=10)
      'payment_amount' => string '159609.00' (length=9)
      'payment_interest' => string '19929.96' (length=8)
      'payment_principle' => string '139679.04' (length=9)

2 个答案:

答案 0 :(得分:3)

这个怎么样?

foreach($array as $k=>$arr)
{
    $array[$k]['payment_amount']    = (float) $arr['payment_amount'];
    $array[$k]['payment_interest']  = (float) $arr['payment_interest'];
    $array[$k]['payment_principle'] = (float) $arr['payment_principle'];
}

答案 1 :(得分:1)

array_walk($arr, function(&$a) {
    $a['payment_amount']    = (float) $a['payment_amount'];
    $a['payment_interest']  = (float) $a['payment_interest'];
    $a['payment_principle'] = (float) $a['payment_principle'];
});

OR

foreach ($arr as &$a) {
    $a['payment_amount']    = (float) $a['payment_amount'];
    $a['payment_interest']  = (float) $a['payment_interest'];
    $a['payment_principle'] = (float) $a['payment_principle'];
}