Anita Mourya - 2 years ago 102

PHP Question

Need subarray difference of below array

`$arr = array(`

array('s'=>'1','e'=>'3'),

array('s'=>'6','e'=>'7'),

array('s'=>'8','e'=>'9'),

array('s'=>'10','e'=>'14'),

array('s'=>'16','e'=>'17'),

)

if(arr[$i][e] - $arr[$i+1][s] <= 1){

//join them

}

else {

//save them as it is

}

Desired result should

`$arr = array(`

array('s'=>'1','e'=>'3'),

array('s'=>'6','e'=>'14'),

array('s'=>'16','e'=>'17'),

)

No consecutive (E-S) should be 1

http://codepad.org/V8omMdn6 is where im struck at

See its like

`iteration 0`

6-3 = 3

so save array('s'=>'1','e'=>'3'),

iteration 1

8-7 = 1

array('s'=>'6','e'=>'9'), => discade in 2 as it

iteration 2

10-9 = 1

array('s'=>'6','e'=>'10'), => discade in 3 as it

iteration 3

10-9 = 1

array('s'=>'6','e'=>'14'),

iteration 4

16-14 = 4

array('s'=>'16','e'=>'17'),

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

I took a very brief look at your codepen, I think what you want to achieve is to find out if the start time of a new session is within a given period from the end time of the last session, if so you would like to combine those sessions.
I think you confused yourself by trying to subtract start time of new session from end time of last session, it should be the other way round.

The way you worded the question made it even more confusing for people to understand.

If my interpretation of your question is correct, the below code should work with the test case you posted here.

```
$arrCount=count($arr)-1;
$output=array();
//call function combineSession
$result=combineSession($arr, $arrCount, $output);
//if consecutive series continue to the last element of the array, then it would return the $temp value therefore result is not false
$output[] = ($result!=FALSE) ? array('s'=> $result, 'e' => $arr[$arrCount]['e']) : $arr[$arrCount];
print_r($output);
function combineSession($arr, $arrCount, &$output){
for ($i=0; $i<$arrCount; $i++){
//if the difference between s and e is less than or equal to one, that there is a consecutive series
if($arr[$i+1]['s']-$arr[$i]['e'] <= 1){
//$temp holds the value of s of the start of a consecutive series to $temp
if (!isset($temp)){
$temp=$arr[$i]['s'];
}
//the consecutive series continue to the last element of the array, outside of the $i range, return value of $temp
if ($i==$arrCount-1){
return $temp;
}
}
//if $temp isn't empty that means, this is the end of a consecutive series, write s and e pair to output, where s=$temp and e=value of key e at current $i to the result then reset $temp
else if (isset($temp)){
$output[]=array('s'=> $temp, 'e' => $arr[$i]['e']);
unset($temp);
}
//not in consecutive series, simply copy s e key value pair to output
else {
$output[]=$arr[$i];
}
}
}
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**