重新格式化数组中的值


Reformat value in array

我有这个数组:

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',
  ),
)

谢谢大家的帮助!

可能是您想要的:

$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);

希望这能帮助您:(

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

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

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

foreach ($array as $item => $data) {
    // remove $
    $array[$item]['price'] = ltrim($array[$item]['price'], '$');
    // format decimals
    $array[$item]['price'] = number_format($array[$item]['price'], 2, '.', '');
}

试试这个,在一个变量中分配你的数组,假设$arr。

foreach($arr as $item=>$val)
{   
    $arr[$item]['price']=number_format(str_replace('$','',$val['price']),2);
}
 print_r($arr); // return your desire array format.

这符合您的要求:

    $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);