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 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答