Forum Moderators: coopster

Message Too Old, No Replies

Handling duplicate array elements

arrays help! (hard)

         

terencepae

3:25 pm on Aug 14, 2007 (gmt 0)

10+ Year Member




$var['item']['quantity'] = 10;

How would I subtract values from a nested array?

Also, if I have duplicates like these..


$var['item'] = 'foo';
$var['item']['quantity'] = 5;
$var['item'] = 'foo';
$var['item']['quantity'] = 11;

How can I sort them out so it looks like this:

$var['item'] = 'foo';
$var['item']['quantity'] = 16;

I tried something like..

function sortCart() {
if (isset($_SESSION['scart'])) {
$cart = $_SESSION['scart'];
return $cart;
} else {
$cart = $_SESSION['cart'];
$dupes = array_count_values($cart);
$keys = array_keys($dupes);
$arr = array();
$counter = count($dupes);
for($i = 0; $i < $counter; $i++) {
$arr[] = array('item' => $keys[$i], 'quantity' => $dupes[$i + 1]);
}
return $arr;
}

array_count_values doesn't work in nested arrays.. but it helps sort out duplicates.. any ideas?

Any help would be appreciated! Thank You!

jatar_k

3:56 pm on Aug 14, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld terencepae,

this case shouldn't happen

$var['item'] = 'foo';
$var['item']['quantity'] = 5;
$var['item'] = 'foo';
$var['item']['quantity'] = 11;

it should be handled in the add to cart portion of your script. Search for an existing item of the same name and add the quantity to what's already there

eelixduppy

3:58 pm on Aug 14, 2007 (gmt 0)



Yup

For this you can use in_array [php.net] to check to see if the value exists already. If it does, then add the new quantity to the one already in the array.

terencepae

4:03 pm on Aug 14, 2007 (gmt 0)

10+ Year Member



If i wanted to add values.. would I do something like..


$value = $var['item']['quantity'];
$newvalue = $value + $quantity;
$var['item']['quantity'] = $newvalue;

How can I subtract values?

Also,

this case shouldn't happen

$var['item'] = 'foo';
$var['item']['quantity'] = 5;
$var['item'] = 'foo';
$var['item']['quantity'] = 11;

happens because I been using array_count_values and it creates multiple keys...

jatar_k

4:08 pm on Aug 14, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



$newvalue = $value - $quantity;

you would need to test to see if it is less than zero and remove the item from the array if it is

eelixduppy

4:12 pm on Aug 14, 2007 (gmt 0)



>> happens because I been using array_count_values and it creates multiple keys...

Are you sure the multiple keys are coming from this function? It shouldn't...

terencepae

4:17 pm on Aug 14, 2007 (gmt 0)

10+ Year Member



i just have something like..

function addcart($value) {
$_SESSION['value'][] = $value;
}

and then it creates an unsorted list..
and using my stupid method, it creates duplicates..

I figured it would be MUCH easier if i just went and used inarray function and add/subtract values...

Thank you!