PHP How do you combine repetitive goods and spit the quantity of goods?



  • Good afternoon. I'm afraid it's not the first day of the task. ♪ ♪

    The goods are issued as a table:

    Title Number

    The cycle foreach is a repetitive product in the table, but the whole repetitive product (on name and code) is no longer available, and the quantity is added to what already exists.

    <?php foreach ($product_data as $product) { ?>
    <tr>
      <td><?php echo $product['name']; ?></td>
      <td><?php echo $product['sku']; ?></td>
      <td class="text-right"><?php echo $product['quantity']; ?></td>
    </tr>
    <?php } ?>
    

    Here's my code. Can you tell me how to be?

    Updating

    My attempts are:

    if(!in_array($product['name'], $sum)) { 
        $sum['name'][] = $product['name'];
    }
    

    if(!in_array($product['sku'], $sum)) {
    $sum['sku'][] = $product['sku'];
    }

    $sum['name'] = array_map("unserialize", array_unique( array_map("serialize", $sum['name'])));
    $sum['sku'] = array_map("unserialize", array_unique( array_map("serialize", $sum['sku'])));

    Accordingly, $sum I've declared it as a mass. Collects everything right. There's only one name left, but how many times do I have the same?



  • Alexander, of course, your code doesn't say much... I don't understand where the mass comes from. product_data ...so it's harder to advise.

    (1) If you're this product_data You take it from the database, you can calm down the request and get all the meanings you need... for example, if we have fields:

    "id ", name ", quantity,

    Then we can take them like this:

    "SELECT id, name, SUM(quantity) as quantity_total FROM mytable GROUP BY id"

    (2) If you're dealing with only the mass, you need to prepare it before you get it.

    $product_data_new = array();
    foreach ($product_data as $product) {
        if (!isset($product_data_new[$product['name']])) {
            $product_data_new[$product['name']] = $product;
        }
        else {
            $product_data_new[$product['name']]['quantity'] += $product['quantity'];
        }
    }
    

    And then I'll take your guy out. $product_data_new:

    <?php foreach ($product_data_new as $product) { ?>
    <tr>
      <td><?php echo $product['name']; ?></td>
      <td><?php echo $product['sku']; ?></td>
      <td class="text-right"><?php echo $product['quantity']; ?></td>
    </tr>
    <?php } ?>
    

    (3) In fact, it is good to immediately record the existence of such a product in the already added and to increase the quantity rather than add another element of the mass.

    I do not claim to be a magnificent beauty and vain of the proposed decisions. As the song goes, "Go on your own, decide on your own..."


Log in to reply
 


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2