Jump to content

Need help assigning array key and value to a string


osaka73

Recommended Posts

I need to assign unknown array keys and their values to strings.

 

The code I am using is:

$cart = $_SESSION['cart'];
$items = explode(',',$cart);
$qty = array();


foreach ($items as $item) {
$qty[$item] = $qty[$item] + 1;
}
print_r($qty);

 

The keys change and are not ordered. I do not know what the key or it's value may be.  So as an example, I might have:

Array ( [2] => 5 [4] => 8 ) 

or in a different scenario, I might have:

Array ( [1] => 6 ) 

 

What those numbers represent is a product id (the key), and the quantity (the value of the key).

 

Can someone help me to assign these to a string?  I have been reading all morning, and not making any progress. 

 

Thank you!

You probably are reading it correctly, but I am still stuck.

 

My thoughts were that if I had an array such as:

Array ( [2] => 5 [4] => 8 ) 

 

I could then do queries to get the product info on the ids for 2 and 4, and multiple the price from the database by the values for [2] and [4].

 

Could you give me a little more help on how I might do that?  I'll keep working with what you showed me (in the meantime), to see if I can work it out.

I think I got what I needed from your help.  But I'm sure I probably took an unnecessary step in the process.

 

Here is what I have now:

$cart = $_SESSION['cart'];
$items = explode(',',$cart);
$qty = array();

foreach ($items as $itemid => $item) {
$qty[$item] = $qty[$item] + 1;
}

$qty = array_unique($qty);
foreach ($qty as $id => $quantity) {
    echo "ID: $id Quantity: $quantity<br />\n";
}

 

And that outputs:

ID: 1 - Quantity: 2

ID: 4 - Quantity: 10

 

I can work with this now and get what I need done.  But if I have taken an unnecessary step, would someone mind correcting me?

 

Thanks!  :D

If you want to use the ID's in a query this will assist you further:

 

$ids = array();
foreach ($items as $itemid => $item) {
$qty[$item] = $qty[$item] + 1;
        $ids[] = $itemid;
}

$sql = "SELECT blah FROM blah WHERE id IN(" . implode(',', $ids) . ")";

 

implode will combine the array and allow for the IN operator (Which acts as an OR statement in MySQL) to select those id's from the database.

[/code]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.