I have two arrays :
$a = array(
array("begin"=>0, "end"=>200,"value"=>90),
array("begin"=>200, "end"=>600,"value"=>50),
array("begin"=>600, "end"=>1000,"value"=>90)
);
$b = array(
array("begin"=>-5, "end"=>50,"value"=>10),
array("begin"=>550, "end"=>590,"value"=>30)
);
Target, merging two arrays with the following criteria:
The answer i would expected:
$result = array(
array("begin"=>-5, "end"=>50,"value"=>10),
array("begin"=>50, "end"=>200,"value"=>90),
array("begin"=>200, "end"=>550,"value"=>50),
array("begin"=>550, "end"=>590,"value"=>30),
array("begin"=>590, "end"=>600,"value"=>50),
array("begin"=>600, "end"=>1000,"value"=>90)
);
What would be the best way to accomplish this? Thank you everyone.
Thanks everyone idea. I just come up with the code and post it here in case if someone have the same problem, they could make reference to.
I first combine the $a and $b to a single array $tmp_combine and sort them according to 'begin'. Construct an unique sorted index array $ind containing all 'start' and 'end' of the $tmp_combine. Then calculate the min value for each index point pair from $tmp_combine, construct an array $ind_SR.
for number of item in $ind_SR, do the merge if they have the same value consecutively and output the final answer to $result.
$tmp_combine = array_orderby(array_merge($a,$b), 'begin', SORT_ASC);
$ind = array_merge(array_column($tmp_combine, 'begin'),array_column($tmp_combine, 'end'));
$ind = array_unique($ind);
asort($ind);
$ind = array_values($ind);
$index = 0;
$ch_now = $ind[0];
for ($i=0; $i<count($ind)-1; $i++){ //calculate the mid pt min value
$mid_pt = ($ind[$i] + $ind[$i+1]) /2;
array_push($ind_SR, find_min_SR($tmp_combine,$mid_pt));
}
for ($i=0; $i<count($ind_SR); $i++){
if ($ch_now <= $ind[$i]){
$start = $ind[$i];
$end = $ind[$i+1];
$result[$index]['begin'] = $ind[$i];
for ($j=$i; $j<count($ind_SR); $j++){
$start_j = $ind[$j];
$end_j = $ind[$j+1];
if ($ind_SR[$j] == $ind_SR[$i]){
$result[$index]['begin'] = $start;
$result[$index]['end'] = $end_j ;
$result[$index]['value'] = $ind_SR[$i];
$ch_now = $ind[$j+1];
} else{
$result[$index]['end'] = $ind[$j] ;
break; break;
}
}
$index++;
}
Use array_merge()
function
$result = array_merge($a,$b);
then use asort()
function to sort array