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
https://forums.phpfreaks.com/topic/217139-php-loop-duplicate-help/
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;
      }
}
?>


$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.

 

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.