重新格式化数组中的值

时间:2013-04-06 05:35:33

标签: php arrays loops

我有这个数组:

array (
  1 => 
  array (
    'name' => 'Product 1',
    'price' => '5',
  ),
  2 => 
  array (
    'name' => 'Product 2',
    'price' => '$10',
  ),
  3 => 
  array (
    'name' => 'Product 3',
    'price' => '$50',
  ),
  4 => 
  array (
    'name' => 'Product 4',
    'price' => '20',
  ),
)

我需要遍历此数组,将所有价格重新格式化为十进制格式。例如,10将是10.00,50将是50.00。我还需要确保从提交$ 50的用户

的用户中删除$

更换这些值后。我需要一个在$ result的值中看起来像这样的数组,所以它看起来像:

array (
  1 => 
  array (
    'name' => 'Product 1',
    'price' => '5.00',
  ),
  2 => 
  array (
    'name' => 'Product 2',
    'price' => '10.00',
  ),
  3 => 
  array (
    'name' => 'Product 3',
    'price' => '50.00',
  ),
  4 => 
  array (
    'name' => 'Product 4',
    'price' => '20.00',
  ),
)

谢谢你的帮助!

5 个答案:

答案 0 :(得分:0)

foreach ($array as &$element) {
  $element['price'] = sprintf("%.2f", str_replace('$', '', $element['price'];
}

在迭代变量之前放置&使其成为对实际元素的引用而不是副本,因此您可以使用赋值对其进行修改。

答案 1 :(得分:0)

试试这个,将数组分配给变量假设$ arr。

foreach($arr as $item=>$val)
{   
    $arr[$item]['price']=number_format(str_replace('$','',$val['price']),2);
}

 print_r($arr); // return your desire array format.

答案 2 :(得分:0)

只需遍历数组,修剪任何$符号,并格式化小数:

foreach ($array as $item => $data) {

    // remove $
    $array[$item]['price'] = ltrim($array[$item]['price'], '$');

    // format decimals
    $array[$item]['price'] = number_format($array[$item]['price'], 2, '.', '');

}

答案 3 :(得分:0)

可能是你想要的:

$result = array (
  1 => 
  array (
    'name' => 'Product 1',
    'price' => '5',
  ),
  2 => 
  array (
    'name' => 'Product 2',
    'price' => '$10',
  ),
  3 => 
  array (
    'name' => 'Product 3',
    'price' => '$50',
  ),
  4 => 
  array (
    'name' => 'Product 4',
    'price' => '20',
  ),
);

$output = array();
foreach($result as $key => $value) {
   $output[$key]['name'] = $value['name'];

   //remove all characters except number and dot.. This will help to remove if instead of $ any other money format comes.
   $new_price = preg_replace("/[^0-9.]/", "", $value['price']);

   $new_price = number_format($new_price, 2, '.', '');
   $output[$key]['price'] = $new_price; 

}

print_R($output);

希望这可以帮助你:)

答案 4 :(得分:0)

这就是你所要求的:

    $arrayhelp = array (
      1 => 
      array (
        'name' => 'Product 1',
        'price' => '5',
      ),
      2 => 
      array (
        'name' => 'Product 2',
        'price' => '$10',
      ),
      3 => 
      array (
        'name' => 'Product 3',
        'price' => '$50',
      ),
      4 => 
      array (
        'name' => 'Product 4',
        'price' => '20',
      ),
    );

^你的阵列V代码

    foreach ($arrayhelp as &$row):

        $row['price'] = number_format(str_replace('$','',$row['price']),2,'.','');
    endforeach;

    print_r($arrayhelp);

如果你想成千上万分开:

    foreach ($arrayhelp as &$row):

        $row['price'] = number_format(str_replace('$','',$row['price']),2,'.',',');
    endforeach;

    print_r($arrayhelp);
相关问题