Created
December 17, 2024 08:47
-
-
Save shohag-cse-knu/a16096da39f91e8352322663089e5f78 to your computer and use it in GitHub Desktop.
Sub array merge in 2D array according to key using PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$source = array( | |
array("1" => 5), | |
array("2" => 1525), | |
array("2" => 12365), | |
array("2" => 34234), | |
array("3" => 324234) | |
); | |
$result = array(); | |
foreach($source as $item) { | |
$artist = key($item); | |
$album = current($item); | |
if(!isset($result[$artist])) { | |
$result[$artist] = array(); | |
} | |
$result[$artist][] = $album; | |
} | |
echo "<pre>"; | |
print_r($result); | |
/* | |
Result: | |
Array | |
( | |
[1] => Array | |
( | |
[0] => 5 | |
) | |
[2] => Array | |
( | |
[0] => 1525 | |
[1] => 12365 | |
[2] => 34234 | |
) | |
[3] => Array | |
( | |
[0] => 324234 | |
) | |
) | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment