如果我有一个类似的数组:
Array
(
[0] => Array
(
[last_year] => 2006
[start_year] => 2000
)
[1] => Array
(
[last_year] => 2008
[start_year] => 2001
)
[2] => Array
(
[last_year] => 1998
[start_year] => 1997
)
)
有没有办法可以比较数组索引并合并彼此之间的last_year
和start_year
?例如,处理后的上述数组应为:
Array
(
[0] => Array
(
[last_year] => 2008
[start_year] => 2000
)
[1] => Array
(
[last_year] => 1998
[start_year] => 1997
)
)
答案 0 :(得分:1)
我能想到的最好方法是:
1) sort this outer array by start_year.
2) iterate over the outer array.
a) If it overlaps with the next array if cur[last_year]>=next[start_year] Then
set cur[last_year]=next[last_year]
b) if it doesn't then cur = next and next is get next array.
这未经过测试,我暂时没有完成PHP。
// You can sort this array however you want, just sort by start_year.
$sortedArray = arr.sort();
$curIndx = 0;
for (int $i=1;$i<len($sortedArray);$i++){
if ($sortedArray[$curIndx][last_year]>=$sortedArray[$i][start_year]){
if (sortedArray[$i][last_year]>=sortedArray[$curIndex][last_year]){
sortedArray[$curIndex][last_year] = sortedArray[$i][last_year];
}
unset(sortedArray[$i]);
} else {
$curIndx = $i;
}
}
答案 1 :(得分:0)
这就是2AM编码产生的,但似乎有用(可能效率不高)。归功于ajon的初始排序提示。
function mergeYears($data) {
usort($data, function($a, $b) { return $a['start_year'] > $b['start_year']; });
do {
$hasMerges = false;
$size = count($data);
$merged = [];
for($i = 0; $i < $size - 1; $i++) {
if ($data[$i+1]['start_year'] >= $data[$i]['start_year'] && $data[$i+1]['start_year'] < $data[$i]['last_year']) {
if ($data[$i]['last_year'] >= $data[$i+1]) {
$lastYear = $data[$i]['last_year'];
} else {
$lastYear = $data[$i+1]['last_year'];
}
$merged[] = ['start_year' => $data[$i]['start_year'], 'last_year' => $lastYear];
$hasMerges = true;
} else {
$merged[] = $data[$i];
}
}
$data = ($hasMerges) ? $merged : $data;
} while ($hasMerges);
return $data;
}
编辑:简化代码
function mergeYears($data) {
usort($data, function($a, $b) { return $a['start_year'] > $b['start_year']; });
for($i = 0; $i < count($data) - 1; $i++) {
if ($data[$i+1]['start_year'] >= $data[$i]['start_year'] && $data[$i+1]['start_year'] < $data[$i]['last_year']) {
$lastYearIndex = ($data[$i]['last_year'] >= $data[$i+1]['last_year']) ? $i : $i + 1;
$merged = [
'start_year' => $data[$i]['start_year'],
'last_year' => $data[$lastYearIndex]['last_year']
];
array_splice($data, $i, 2, [$merged]);
$i--;
}
}
return $data;
}