dongliuzi3410 2018-03-01 03:44
浏览 87
已采纳

通过匹配关键php中的字符串对数组中的项进行分组

I have an array where I want to group items having match strings in key.

My array looks like this:

 Array
 (
     [ALL_trading_enabled] => 1
     [ALL_enabled_pairs] => ALL
     [ALL_max_trading_pairs] => 10
     [SNGLSBTC_DCA_enabled] => 
     [SNGLSBTC_sell_only_mode] => 1
     [SNGLSBTC_sell_value] => 0.28
     [SNGLSBTC_trailing_profit] => 0.009
     [ENJBTC_DCA_enabled] => 
     [ENJBTC_sell_only_mode] => 1
     [ENJBTC_sell_value] => 0.28
     [ENJBTC_trailing_profit] => 0.009
     [BCPTBTC_DCA_enabled] => 
     [BCPTBTC_sell_only_mode] => 1
     [BCPTBTC_sell_value] => 0.28
     [BCPTBTC_trailing_profit] => 0.009
 )

I want to group the items that have the same string. What I want looks like this:

 Array
 (
    [0] => Array(
            [ALL_trading_enabled] => 1
            [ALL_enabled_pairs] => ALL
            [ALL_max_trading_pairs] => 10
          )
    [1] => Array(
            [SNGLSBTC_DCA_enabled] => 
            [SNGLSBTC_sell_only_mode] => 1
            [SNGLSBTC_sell_value] => 0.28
            [SNGLSBTC_trailing_profit] => 0.009
          )
    [2] => Array(
            [ENJBTC_DCA_enabled] => 
            [ENJBTC_sell_only_mode] => 1
            [ENJBTC_sell_value] => 0.28
            [ENJBTC_trailing_profit] => 0.009
          )
    [3] => Array(
            [BCPTBTC_DCA_enabled] => 
            [BCPTBTC_sell_only_mode] => 1
            [BCPTBTC_sell_value] => 0.28
            [BCPTBTC_trailing_profit] => 0.009
          )
 )

Any help to achieve this? Or better yet if I can assign the match as the key for the created group.

 Array(
    [ALL] => Array(
             //items here
             )
    [SNGLSBTC] => Array(
                  //items here
                  )
 )
  • 写回答

1条回答 默认 最新

  • dongsi3826 2018-03-01 03:51
    关注

    Explode on _ and get the first portion, use as the key and add to that array:

    foreach($array as $key => $value) {
        $new_key = explode('_', $key)[0];
        $result[$new_key][$key] = $value;
    }
    

    If needed to re-index (after your edit you don't need this):

    $result = array_values($result);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?