合并关联数组与相同的值?

I have an associative array -

{
"1":{"list_price_9":"1250.0000","list_price_18":"1250.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"2":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"3":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"4":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"5":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"6":{"list_price_9":"2500.0000","list_price_18":"2500.0000","golflan_price_9":"0.0000","golflan_price_18":"2500.0000"},
"7":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"2500.0000"}
}

I want to convert the array such that the resulting array has merged the keys with similar values in a comma separated string.

So the result will be something like this -

{
"1":{"list_price_9":"1250.0000","list_price_18":"1250.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"2,3,4,5,7":{"list_price_9":"0.0000","list_price_18":"0.0000","golflan_price_9":"0.0000","golflan_price_18":"1250.0000"},
"6":{"list_price_9":"2500.0000","list_price_18":"2500.0000","golflan_price_9":"0.0000","golflan_price_18":"2500.0000"}
}

This seems simple, but I am not being able to come up with an elegant solution for this. Kindly help.

I tried something like this -

  $common_prices = array();
  foreach ($pricelist as $day => $prices) {
    foreach ($common_prices as $new_day => $new_prices) {
      if($prices === $new_prices) {
        $modified_day = $new_day.','.$day;
        $common_prices[$modified_day] = $new_prices;
        unset($new_day);
      }
    }
    $common_prices[$day] = $prices;
  }

where $pricelist is the given array and $common_prices is the expected array. But obviously this will not work.

You can do it with linear complexity using intermediate array of accumulated keys for unique values:

$keys = [];

foreach($pricelist as $key=>$val) {
  $str = json_encode($val);
  if(!isset($keys[$str])) {
    $keys[$str] = [];
  }
  $keys[$str][] = $key;
}

$common_prices = [];
foreach($keys as $key=>$val) {
  $common_prices[join(',',$val)] = json_decode($key);
}

You can just aggregate keys and data in the separated arrays and then combine them.

Example:

$keys = [];
$data = [];

foreach ($pricelist as $day => $prices) {
    if ($key = array_search($prices, $data))
        $keys[$key] .= ',' . $day;
    else {
        $keys[] = $day;
        $data[] = $prices;
    }
}

$common_prices = array_combine($keys, $data);