我们说我有一个这种格式的药物数据库:
-----------------------------------------------
| Medication Name | Strength | Unit |
-----------------------------------------------
| NORCO | 5;325 | mg/1;mg/1 |
| Amoxicillin | 500 | mg/1 |
| Augmentin | 250;62.5 |mg/5mL; mg/5mL|
-----------------------------------------------
如何使用php以这种方式显示数据:
NORCO 5mg/325mg
Amoxicillin 500mg
Augmentin 250mg/5mL 62.5mg/5mL
使用/1
可以轻松地从单位列中删除str_replace
但是如何使用分号分隔单位来强调单位?
答案 0 :(得分:1)
您可以使用php explode
功能。可能还有其他更好的解决方案,对于初学者,您可以尝试下面的代码。
// Considering this is your data from database
$data = array(
array(
'name' => "NORCO",
'strength' => "5;325",
'unit' => "mg/1;mg/1"
),
array(
'name' => "Amoxicillin",
'strength' => "500",
'unit' => "mg/1"
),
array(
'name' => "Augmentin",
'strength' => "250;62.5",
'unit' => "mg/5mL; mg/5mL"
),
);
// Looping through data
foreach ($data as $row) {
$strength = explode(';', $row['strength']);
$unit = explode(';', $row['unit']);
$combine = combineStrengthUnit($strength, $unit);
echo $row['name'] . " " . $combine ;
echo "<br/>";
}
// return combined Strength and Units
function combineStrengthUnit($strength, $unit)
{
$combine_result = '';
foreach ($strength as $key => $value) {
$combine_result .= $value . trim(str_replace('/1', '', $unit[$key])) . " "; //trimming the spaces of unit
}
return $combine_result;
}
<强>输出:强>
NORCO 5mg 325mg
Amoxicillin 500mg
Augmentin 250mg/5mL 62.5mg/5mL