Kaboom Kaboom - 5 months ago 13
PHP Question

PHP - Pulling array and splitting the strings

Not sure how to title this properly but here's the issue I am running into currently. I built a cart and checkout system and it loads all the data into a database when it finalized the order. To save some space, I stored just the item IDs originally but then I ran into the issue of if I deleted the item from the database (because it was discontinued or whatever) then it wouldn't return the info I needed. And if they ordered more then 1 item the database record would be wrong. So I stored the data like so:

Itemid:Quantity:Price:name, itemid2:quantity2:price2:name2


OR

1:3:20.00:Flower Hat, 2:1:17.75:diamonds


The issue I have right now that I need help with is this. I need to seperate the four values into variables like
$price
,
$item
,
$id
,
$ammount
so I can display them on the order history page and I need to loop through all items on the array so I can print a row for each item with all four fields respective to that item.

I use strpos already to get the shipping info from the same database field which is formatted as METHOD:Price but since I have 3 :'s on my string I'm not sure how to go through each one. Thanks.

Answer

Here's a function

function parseItems($dbjunk){
    $cart = array();
    $items = explode(",",$dbjunk);
    foreach($items as $i){
        $chunks = explode(":", $i);
        $cart[] = array(
            "ItemID" => $chunks[0] ,
            "Quantity" => $chunks[1] ,
            "Price" => $chunks[2] ,
            "name" => $chunks[3]
        );
    }
    return $cart;
}

Example usage:

$dbjunk = "Itemid:Quantity:Price:name, itemid2:quantity2:price2:name2";
$parsed = parseItems($dbjunk);
print_r($parsed);

See: https://3v4l.org/rBkXF

If you need variables instead of an array you can use list(), like this..

$dbjunk = "Itemid:Quantity:Price:name, itemid2:quantity2:price2:name2";
$parsed = parseItems($dbjunk);
foreach($parsed as $p){
    list($itemID, $Quantity, $Price, $name) = array_values($p);
    var_dump($itemID, $Quantity, $Price, $name);
}

see: https://3v4l.org/l4vsn