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

时间:2017-09-08 08:22:11

标签: php arrays 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"}
}

我想转换数组,以便生成的数组在逗号分隔的字符串中合并了具有相似值的键。

所以结果会是这样的 -

{
"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"}
}

这看起来很简单,但我无法为此提出一个优雅的解决方案。 请帮助。

我尝试过这样的事情 -

  $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;
  }

其中$ pricelist是给定的数组,$ common_prices是预期的数组。但显然这不起作用。

2 个答案:

答案 0 :(得分:3)

您可以使用线性复杂度使用累积键的中间数组来获取唯一值:

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

答案 1 :(得分:2)

您可以在分离的数组中聚合键和数据,然后将它们组合起来。

示例:

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