phparraysgroupingassociative-arraysub-array

Group values of an associative array by key prefix


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

Solution

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