views:

31

answers:

1

How can I group same values in a multidimention array?

I want this

array(
  array('a' => 1, 'b' => 'hello'), 
  array('a' => 1, 'b' => 'world'), 
  array('a' => 2, 'b' => 'you')
)

to become

array(
  array(
    array('a' => 1, 'b' => 'hello'), 
    array('a' => 1, 'b' => 'world')
  ), 
  array('a' => 2, 'b' => 'you')
)
+1  A: 
function array_gather(array $orig, $equality) {
    $result = array();
    foreach ($orig as $elem) {
        foreach ($result as &$relem) {
            if ($equality($elem, reset($relem))) {
                $relem[] = $elem;
                continue 2;
             }
        }
        $result[] = array($elem);
    }
    return $result;
}

then

array_gather($arr,
    function ($a, $b) { return $a['a'] == $b['a']; }
);

This could be implemented in a more efficient matter if all your groups could be reduced to a string value (in this case they can, but if your inner arrays were something like array('a' => ArbitraryObject) they could not be).

Artefacto
Thanks! It works perfect!
Codler