Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shohag-cse-knu/a16096da39f91e8352322663089e5f78 to your computer and use it in GitHub Desktop.
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
<?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