Dale Nguyen Dale Nguyen - 6 months ago 15
PHP Question

How to combine multi - Arrays with the same key?

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,

Answer

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 ▶}
  ]
]

After you can do second foreach:

$outputArray = [];
foreach ($outputArray as $key => $value) {
    $outputArray[] = array_merge([$key], $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 ▶}
  ]
]
Comments