JamesG JamesG - 15 days ago 5
PHP Question

PHP: how to process this data from database

I'm pretty new to programming so I'm sorry if this is very nooby.

In a dummy database I have a column called currencies. The column has this data:

36:USD,74:GBP,68:USD,119:USD,114:BGN,15:USD,32:GBP,1:BGN


Above data is the amount and its respective currency the user has paid.

What I want to do is to display a table with each currency and the total amount of sales for that country and also display it in table form.

So with the above data, I want the output below:

Currency | # Sales
____________________

USD 4
GPB 2
BGN 2
____________________

Total: 8

Answer

Try this

$data = "36:USD,74:GBP,68:USD,119:USD,114:BGN,15:USD,32:GBP,1:BGN";
$data = explode(",", $data);

$result = array();
foreach ($data as $value) {
    $d_array = explode(":", $value);
    if(isset($result[$d_array[1]]))
        $result[$d_array[1]] +=1;
    else
        $result[$d_array[1]] = 1;
}
$total = count($data);

var_dump($result);
var_dump($total);

And the result

array (size=3)
'USD' => int 4
'GBP' => int 2
'BGN' => int 2

int 8
Comments