有选择地格式化数组中的值

时间:2019-01-25 04:10:13

标签: php

给出数组中的数据,我想格式化数字值,以便显示2个小数位和数字分隔符。这是一个示例:

$array = [
'accountID' => 1000,
'scenarioID' => 2,
'income' => 34560.78,
'expenses' => 1500,
'comments' => 'abc'
];

$formatted_array = array_map(
 function($value) { return is_numeric($value) ? number_format($value, 2) : $value; },
 $array);

echo '<pre>' . print_r($formatted_array, 1) . '</pre>';

这是上面代码的结果:
enter image description here

但是,作为ID的数组中的键/值对不应该显示小数位或数字分隔符-需要将它们从数字格式中排除。为了解决这个问题,我尝试如下替换$formatted_array

$formatted_array = array_walk(
$array, function(&$value, $key) { return (is_numeric($value) and !in_array($key, ['accountID', 'scenarioID'])) ? number_format($value, 2) : $value; });

,但是什么也不返回,也没有错误信息。在array_walk版本中需要修改哪些内容才能使其按需工作?

0 个答案:

没有答案