-1

Let us say that I have a medication database with this format:

-----------------------------------------------
| Medication Name |  Strength  |    Unit      |
-----------------------------------------------
| NORCO           |   5;325    |  mg/1;mg/1   |
| Amoxicillin     |     500    |     mg/1     |
| Augmentin       |  250;62.5  |mg/5mL; mg/5mL|
-----------------------------------------------

How can I display data in this way using php:

NORCO 5mg/325mg
Amoxicillin 500mg
Augmentin 250mg/5mL 62.5mg/5mL

removing /1 from the unit column is easy using str_replace but how can I distribute units to strengths with a semicolon separating them?

syrkull
  • 2,295
  • 4
  • 35
  • 68
  • Please show what you've tried so far. – Indrasis Datta Jul 03 '16 at 05:19
  • 1
    Even if someone gives you a query here, you should really _normalize_ your database and do away with those semicolon-separated lists. – Tim Biegeleisen Jul 03 '16 at 05:21
  • 3
    trust me, I would have done that.. but the government does not. the source of the database is from the food and drug administration (FDA). source: http://www.fda.gov/Drugs/InformationOnDrugs/ucm142438.htm – syrkull Jul 03 '16 at 05:22
  • 2
    I'm not surprised, and I also would not be surprised if the author of this table were promoted several times. Have a look [here](http://stackoverflow.com/questions/2696884/split-value-from-one-field-to-two) to get started thinking. – Tim Biegeleisen Jul 03 '16 at 05:26
  • 1
    You can split the string by split function in php or mysql query. But by php it is simpler. – Mostafa Vatanpour Jul 03 '16 at 06:08

1 Answers1

1

You can use php explode function. There might be other better solutions, for starters you can try below code.

// 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;
}

Output:

NORCO 5mg 325mg
Amoxicillin 500mg
Augmentin 250mg/5mL 62.5mg/5mL 
T. D. Ben
  • 303
  • 2
  • 11