Jump to content

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]

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.