Jump to content

php loop duplicate help


MDanz

Recommended Posts

foreach ($items as $product ) {
echo $product;
?><input type="text" size="2" value="<?php  
\\display quantity here
  ?>" name="quantity" /><?php
}

 

$items is an array.  It has multiple values, some duplicate. How do i count the duplicate values in the array and display in this foreach loop?

 

i know array_count_values($product) but putting that in the foreach loop won't accomplish what i want.

 

another thing. i can get the foreach loop  to not display duplicates by doing this

 

foreach (array_unique($items) as $product ) {
echo $product;
?><input type="text" size="2" value="<?php  
\\display quantity here
  ?>" name="quantity" /><?php
}

 

how would i accomplish both.

 

basically i want it to display the quantity without displaying duplicate rows.  aka shopping cart.

Link to comment
Share on other sites

You should probably use a multidimensional array for this, so that you could store the quantity, product name and eventually a price too probably, in the same array.

 

For instance if your products comes from a database.

 

This won't exactly solve your issue, this is merely another way of doing it and you will have to look other places for further instruction in building a shopping cart this way.

 

<?php

$items = array();


  function addToCart($productId) {
       if(array_key_exists($productId, $items)) {
          // the product id is already in the array, increment the quantity
          $items[$productId]['quantity']++;
      } else {
          $items[$productId]['quantity'] = 1;
      }
}
?>

Link to comment
Share on other sites


$quantity = array_count_values($items);
$items    = array_unique($items);
foreach($items as $product):

   echo $product . '  <input type="text" size="2" value="' . $quantity[$product] . '" /><br />';

endforeach;

 

EDIT: forgot array_unique.

 

Link to comment
Share on other sites

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.