I'm working in PHP and I need a function that will merge user specified sub-arrays within a 2D array into a new array, e.g.
$arr = [
"sub_1" => [ "a", "b" ],
"sub_2" => [ "c", "d" ],
"sub_3" => [ "e", "f" ],
"sub_a" => [ 1, 2, 3 ],
"sub_b" => [ 4, 5, 6 ],
"sub_c" => [ 7, 8, 9 ]
];
merge_subs( $arr, [ "sub_1", "sub_2", "sub_3" ] );
// should return: [ "a", "b", "c", "d", "e", "f" ]
merge_subs( $arr, [ "sub_a", "sub_b", "sub_c" ] );
// should return: [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
What is the most efficient way to go about this?
EDIT:
This is what I tried but it doesn't work so I am clearly doing something wrong.
function merge_subs( $arr, $subs ){
$new = [];
foreach( $subs as $sub ){
array_push( $new, $arr[$sub] );
}
return array_merge( $new );
}
EDIT 2:
I realized I left out the ellipsis and now I have it working. At any rate, I want to know if there is a better way to accomplish this.
array_merge()if you had!$x = array_merge($arr['sub_1'], $arr['sub_2'], $arr['sub_3']); print_r($x);