开发者

How can I group same values in a multidimention array?

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'), 
    arr开发者_开发百科ay('a' => 1, 'b' => 'world')
  ), 
  array('a' => 2, 'b' => 'you')
)


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜