duanjian4150 2017-09-08 08:22
浏览 25
已采纳

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

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.

  • 写回答

2条回答 默认 最新

  • douzhi3586 2017-09-08 08:50
    关注

    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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化