开发者

PHP merge similar values in an array

$arr = (a => array(1,2,3), b => array(1,2,3), c => array(4,5), d=> array(8,9,10), e => array(8,9), f => array(9,10);

I would like to merge similar values, so that I would get:

  • Problem #1 (similar values, harder):

$new_arr = (a_b => array(1,2,3), c => (4,5), d_e_f => array(8,9,10));

  • Problem #2 (exactly same values, easier):

$new_arr 开发者_高级运维= (a_b => array(1,2,3), c => (4,5), d => array(8,9,10), e => array(8,9), f => array(9,10));

What's the most effective way to to the above?? May be a hard question to solve :D

Thanks!


I'd call this finding the "connected components" of a graph.

http://en.wikipedia.org/wiki/Connected_component_%28graph_theory%29


$unique=array_unique($arr,SORT_REGULAR);
foreach (array_diff_key($arr,$unique) as $key=>$value) {
    $oldkey=array_search($value,$unique);
    unset($unique[$oldkey]);
    $unique[$oldkey.'_'.$key]=$value;
}
var_dump($unique);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜