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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘