我可以简化此代码吗?我从SELECT
查询中获取了五个字符串,将它们拆分为仅数字并添加它们。
$sum = preg_replace("/[^0-9]/","",$row['AB']) + preg_replace("/[^0-9]/","",$row['CD']) + preg_replace("/[^0-9]/","",$row['EF']) + preg_replace("/[^0-9]/","",$row['GH']) + preg_replace("/[^0-9]/","",$row['IJ']);
我可以这样做:
preg_replace("/[^0-9]/","",$sum = $row['AB'] + $row['CD'] + $row['EF'] + $row['GH'] + $row['IJ']);
答案 0 :(得分:1)
您可以编写一个简单的循环来减少代码重复:
如果您的sql仅选择所需的列:
$sum = 0;
foreach($row as $item)
$sum += preg_replace("/[^0-9]/","",$item);
如果行中有更多列(并且您实际上需要这些数据,因此您无法更改SQL):
$sum = 0;
foreach(['AB','CD','EF','GH','IJ'] as $key)
$sum += preg_replace("/[^0-9]/","",$row[$key]);