dongliuzi3410 2018-02-28 19: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-02-28 19: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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部