Grouping array contents
June 10, 2008 – 4:02 pmSource data:
-
$triples = array();
-
$triples[] = array('VISA','EUR',13);
-
$triples[] = array('VISA','EUR',26);
-
$triples[] = array('VISA','EUR',39);
-
$triples[] = array('VISA','JPY',13);
-
$triples[] = array('PAYPAL','JPY',13);
Desired result
-
array(
-
array('VISA','EUR',78),
-
array('VISA','JPY',13),
-
array('PAYPAL','JPY',13)
-
)
e.g. group data by both payment method and currency.
My solution
-
$triples = array();
-
$triples[] = array('VISA','EUR',13);
-
$triples[] = array('VISA','EUR',26);
-
$triples[] = array('VISA','EUR',39);
-
$triples[] = array('VISA','JPY',13);
-
$triples[] = array('PAYPAL','JPY',13);
-
-
-
$result = array();
-
foreach($triples as $key => $value)
-
{
-
$lookup_key = $value[0] . '-' . $value[1];
-
if (array_key_exists($lookup_key, $result)) {
-
$result[$lookup_key][2] += $value[2];
-
} else {
-
$result[$lookup_key] = $value;
-
}
-
}
-
-
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?
