Search code examples
phparraysarray-merge

Merge keys of an array based on values


I want to merge the keys of array based on values. This is my array.

Array
(
    [1] => 1
    [2] => 1
    [3] => 1
    [4] => 2
    [5] => 0
    [6] => 2
    [7] => 2
)

I want output as

Array
(
    [1,2,3] => 1
    [4,6,7] => 2
    [5] => 0
)

I have been brain storming entire day but couldn't find a solution. Any hint would be much appreciated.

WHAT I HAVE TRIED:

for($i=2;$i<=count($new);$i++){
    if ($new[$i-1][1]==$new[$i][1]){
        $same .= $new[$i-1][0].$new[$i][0];
    }
}
echo $same;

But I am stucked. I am comparing the keys one by one but it's very complicated. I don't need the code. I only need the hint or logic. Anyone kind enough?


Solution

  • <?php
    $old_arr = ["1"=>1,"2"=>1,"3"=>1,"4"=>2,"5"=>0,"6"=>2,"7"=>2];
    $tmp = array();
    foreach($old_arr as $key=>$value)
    {
      if(in_array($value, $tmp)){
          $index = array_search($value, $tmp);
          unset($tmp[$index]);
          $tmp[$index.",".$key] = $value;
      }else{
        $tmp[$key] = $value;
      }
    }
    ksort($tmp);
    echo "<pre>";
    print_r($tmp);
    echo "</pre>";
    ?>
    

    https://eval.in/529314