0

$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!

1
  • A possible first step for #2 (a version of array_unique that works with arrays, but doesn't create a_b key names) is in the User Contributed Notes to array_unique: php.net/manual/en/function.array-unique.php#97285 Commented Aug 14, 2010 at 10:20

2 Answers 2

1

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

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

Sign up to request clarification or add additional context in comments.

Comments

0
$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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.