1

I'm trying to write a script that will make produce an easy overview over a list of orders.

I have an array that looks like this:

Array(

    [0]=>Array(
              [0] => name of product 1
              [1] => name of options for product
              [3] => quantity (an integer)
              )
    [1]=>Array(
              [0] => name of product 2
              [1] => name of options for product
              [3] => quantity (an integer)
              )
    etc.
)

What I want to do is to check where keys [0] and [1], i.e the same product with the same options, and remove duplicates. At the same time, I want the value [3] to be incremented with the number in the arrays that were removed. To simplify, I want to merge value [3] where product and options match. I've been thinking about this for a long time but can't figure out how to do it. Any suggestions?

2 Answers 2

3

You can loop over the array and use an associative array to "count" the products:

$merged = array();

foreach($products as $product) {
    $key = $product[0] . $product[1];
    if(!array_key_exists($key, $merged)) {
        $merged[$key] = $product;
    }
    else {
        $merged[$key][3] += $product[3];
    }
}

The trick here is that the name and the options of a product are concatenated to form a unique product key. Of course that requires that the options for a product are always in the same order.

Working Demo

Sign up to request clarification or add additional context in comments.

1 Comment

Wow! This is a terrific script for my purpose. I was experimenting with in_array() before but I didn't get very far. Thanks alot!
0

Dual loops

<?php
for($counter=0;$counter<count($arr)-1;$counter++){
  $counter2 = $counter+1;
  while($counter2<count($arr)) {
    if( $arr[$counter][0] == $arr[$counter2][0] &&
        $arr[$counter][1] == $arr[$counter2][1] ) {
       // Same product
       $arr[$counter][2]+=$arr[$counter2][2];
       array_splice($arr, $counter2, 1);
    } else {
      $counter2++;
    }
  }
}
?>

2 Comments

Note that this is O(n^2) which will be horribly slow on large lists.
True, but, if $arr only has one reference, the array_splice will not allocate new memory for an array. Making a copy of an array which you may or may not remove elements will at most double the memory usage. With a large list you have higher chance of running out of available php memory.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.