php - assort merge two assorted arrays -
i trying merge 2 assorted arrays assorting result in php code have managed come with:
<?php function assotassortedarrays($a, $b){ if (empty($a)){ return $b; } if (empty($b)){ return $a; } if ($a[0] < $b[0]){ return array_merge($a[0], array_merge(array_slice($a, 1, count($a)-1), $b)); } else { return array_merge($b[0], array_merge(array_slice($b, 1, count($b)-1), $a)); } } $a = array(1,2,3,4,5); $b = array(3,4,5,6,7); var_dump(assotassortedarrays($a, $b));
the code not work, error getting:
warning: array_merge(): argument #1 not array in d:\web\a\sortarrays.php on line 14
basically interpreter saying argument 1 here array_merge(array_slice($b, 1, count($b)-1), $a));
not , array, have done print_r on elements , says arrays. doing wrong?
edit, sam correct code:
function mergearrays($a, $b){ if (empty($a)){ return $b; } if (empty($b)){ return $a; } if ($a[0] < $b[0]){ $aux[] = $a[0]; return array_merge($aux, mergearrays(array_slice($a, 1, count($a)), $b)); } else { $aux[] = $b[0]; return array_merge($aux, mergearrays(array_slice($b, 1, count($b)), $a)); } }
i think error message might misleading, actual problem call array_merge
before array_merge(array_slice(...
.
the values of $a[0]
, $b[0]
not arrays.
Comments
Post a Comment