dongqiu7365 2016-05-04 17:20
浏览 40
已采纳

如何将多个数组与相同的键组合?

I have an array like this. There are some array with the same name. Such as Grant 1, Grant 2... and they have many Projects that should be in the same place. For example: Grant 1 should contain the information that belongs to Grant 1. The same thing that should happen to Grant 2. And so on

array:5 [▼
  0 => array:2 [▼
    0 => "Grant 1"
    1 => Project {#423 ▶}
  ]
  1 => array:2 [▼
    0 => "Grant 1"
    1 => Project {#421 ▶}
  ]
  2 => array:2 [▼
    0 => "Grant 2"
    1 => Project {#412 ▶}
  ]
  3 => array:2 [▼
    0 => "Grant 1"
    1 => Project {#424 ▶}
  ]
  4 => array:2 [▼
    0 => "Grant 2"
    1 => Project {#419 ▶}
  ]
]

I want to combine them to:

array:5 [▼
  0 => array:2 [▼
    0 => "Grant 1"
    1 => Project {#423 ▶}
    2 => Project {#421 ▶}
    3 => Project {#424 ▶}
  ]
  1 => array:2 [▼
    0 => "Grant 1"        
    1 => Project {#412 ▶}
    2 => Project {#419 ▶}
  ]
]

Please help. Thanks,

  • 写回答

1条回答 默认 最新

  • dongluxin2452 2016-05-04 17:22
    关注

    I think you can use foreach:

    $newArray = [];
    foreach ($array as $value) {
        $newArray[$value[0]][] = $value[1];
    }
    

    And you have array like this:

    array:5 [▼
      "Grant 1" => array:2 [▼
        1 => Project {#423 ▶}
        2 => Project {#421 ▶}
        3 => Project {#424 ▶}
      ]
      "Grant 2" => array:2 [▼ 
        1 => Project {#412 ▶}
        2 => Project {#419 ▶}
      ]
    ]
    

    Or something like this(thanks @AbraCadaver):

    $newArray = [];
    foreach ($array as $value) {
        if (isset($newArray[$value[0]] {
            $newArray[$value[0]][] = $value[1];
        } else {
            $newArray[$value[0]] = $value;
        }
    }
    

    Array what you need:

    array:5 [▼
        0 => array:2 [▼
            0 => "Grant 1"
            1 => Project {#423 ▶}
            2 => Project {#421 ▶}
            3 => Project {#424 ▶}
      ]
        1 => array:2 [▼
            0 => "Grant 1"        
            1 => Project {#412 ▶}
            2 => Project {#419 ▶}
      ]
    ]
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 Oracle中如何从clob类型截取特定字符串后面的字符
  • ¥15 想通过pywinauto自动电机应用程序按钮,但是找不到应用程序按钮信息
  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序