Grouping array contents

June 10, 2008 – 4:02 pm

Source data:

  1. $triples = array();
  2. $triples[] = array('VISA','EUR',13);
  3. $triples[] = array('VISA','EUR',26);
  4. $triples[] = array('VISA','EUR',39);
  5. $triples[] = array('VISA','JPY',13);
  6. $triples[] = array('PAYPAL','JPY',13);

Desired result

  1. array(
  2.     array('VISA','EUR',78),
  3.     array('VISA','JPY',13),
  4.     array('PAYPAL','JPY',13)
  5. )

e.g. group data by both payment method and currency.
My solution

  1. $triples = array();
  2. $triples[] = array('VISA','EUR',13);
  3. $triples[] = array('VISA','EUR',26);
  4. $triples[] = array('VISA','EUR',39);
  5. $triples[] = array('VISA','JPY',13);
  6. $triples[] = array('PAYPAL','JPY',13);
  7.  
  8.  
  9. $result = array();
  10. foreach($triples as $key => $value)
  11. {
  12.     $lookup_key = $value[0] . '-' . $value[1];
  13.     if (array_key_exists($lookup_key, $result)) {
  14.         $result[$lookup_key][2] += $value[2];
  15.     } else {
  16.         $result[$lookup_key] = $value;
  17.     }
  18. }
  19.  
  20. print_r($result);

Downside - data is accessed by numberic key, which is generally not a good thing to do. This however is just a proof of concept, in real life you probably have names for your columns.

Can you write a shorter and more elegant solution?

Post a Comment