需要下面阵列的子阵差
$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[$arr[$i+1][s] - $i][e] <= 1){
//join them
}
else {
//save them as it is
}
期望的结果
$arr = array(
array('s'=>'1','e'=>'3'),
array('s'=>'6','e'=>'14'),
array('s'=>'16','e'=>'17'),
)
没有连续的(下一个S)应该是1
http://codepad.org/V8omMdn6是我攻击的地方
看它的样子
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'),
发布于 2016-06-17 05:36:47
$result = [];
foreach ($arr as $pair) {
if (empty($result) || $pair['s'] - end($result)['e'] > 1) {
$result[] = $pair;
} else {
$result[key($result)]['e'] = $pair['e'];
}
}
您还可以使用$last
作为键,而不是使用end()
& key()
来提高可读性。在$result
上使用数组指针函数可以缩短代码,但使用一些丑陋的隐藏效果。end($result)
返回数组的最后一个元素(使用带函数结果的键括号是可能的,因为我猜是php5.3 ),但也设置了指针,所以如果需要的话,key($result)
将返回正确的键。
当迭代您处理结果数组的最后一个元素时,这个元素可能不会立即生效,但是您不需要向前看。最后一个元素有两种场景(空$result
的初始状态条件):
e
值发布于 2016-06-16 20:49:35
我简单地看了一下你的代码库,我想你想要的是找出新一届会议的开始时间是否在上一届会议结束后的一段时间内,如果是这样的话,你想把这些会议结合起来。我认为你试图从上一次会议结束时减去新会话的开始时间,这应该是另一回事。
你提出这个问题的方式使人们更加难以理解。
如果我对您的问题的解释是正确的,下面的代码应该适用于您在这里发布的测试用例。
function combineSession($arr){
$arrCount=count($arr)-1;
for ($i=0; $i<$arrCount; $i++){
//if the difference between s and e is less than or equal to one, then there is a consecutive series
if($arr[$i+1]['s']-$arr[$i]['e'] <= 1){
//assign the value of s at the start of a consecutive series to $temp
if (!isset($temp)){
$temp=$arr[$i]['s'];
}
//if consecutive series ends on the last sub_array, write $temp e pair to output
if ($i==$arrCount-1){
$output[]= array('s'=> $temp, 'e' => $arr[$arrCount]['e']);
}
}
//end of a consecutive series, write $temp and e pair to output, unset $temp
else if (isset($temp) && $i<$arrCount-1){
$output[]=array('s'=> $temp, 'e' => $arr[$i]['e']);
unset($temp);
}
//consecutive series ended at the second last sub-array, write $temp and e pair to output and copy key value pair of the last sub-array to output
else if ($i==$arrCount-1){
$output[]=array('s'=> $temp, 'e' => $arr[$i]['e']);
$output[]=$arr[$arrCount];
}
//not in a consecutive series, simply copy s e key value pair to output
else {
$output[]=$arr[$i];
}
}//end of for loop
print_r($output);
}//end of function
发布于 2016-06-23 10:32:21
如果($i=$arrCount-1){ $output[]=!isset($temp)?$arr$i:$arr$i(‘s’> $temp,'e‘=> $arr$i);$output[]=$arr$arrCount};
https://stackoverflow.com/questions/37856752
复制相似问题