note 90243 deleted from function.array-merge by danbrown
| From: | danbrown@php.net | Date: | Sun, 12 Apr 2009 03:32:12 +0000 |
| Subject: | note 90243 deleted from function.array-merge by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-153108@lists.php.net to get a copy of this message | ||
Note Submitter: ironiridis at gmail dot com
----
Untested, so use at your own risk...
I came to this page perhaps looking for some code to merge ranges represented by arrays of start/end
pairs. Here's what I came up with:
<?php
function range_merge($a, $b, $s = 's', $e = 'e')
{
if (!isset($a[$s]) or !isset($a[$e]) or !isset($b[$s]) or !isset($b[$e]))
return(false);
// ensure that the "start" and "end" values are numerically coherant
if ($a[$s] > $a[$e]) $a = array('s'=>$a[$e], 'e'=>$a[$s]);
if ($b[$s] > $b[$e]) $b = array('s'=>$b[$e], 'e'=>$b[$s]);
if ($a[$s] == $b[$e]) // a starts where b ends
return(array('s'=>$b[$s],'e'=>$a[$e]));
if ($b[$s] == $a[$e]) // b starts where a ends
return(array('s'=>$a[$s],'e'=>$b[$e]));
if ($a[$s] >= $b[$s] and $a[$s] < $b[$e]) // a starts in b
return(array('s'=>$b[$s],'e'=>max($b[$e], $a[$e])));
if ($b[$s] >= $a[$s] and $b[$s] < $a[$e]) // b starts in a
return(array('s'=>$a[$s],'e'=>max($b[$e], $a[$e])));
if ($a[$e] > $b[$s] and $a[$e] <= $b[$e]) // a ends in b
return(array('s'=>min($b[$s], $a[$s]),'e'=>$b[$e]));
if ($b[$e] > $a[$s] and $b[$e] <= $a[$e]) // b ends in a
return(array('s'=>min($b[$s], $a[$s]),'e'=>$a[$e]));
return(false);
}
function range_merge_all($r)
{
if (!is_array($r)) return(false);
$t = array(); // return value
while(sizeof($r)) // while we have values left to pop
{
$g = array_pop($r);
if (sizeof($r)) // $g might have popped the last value off
foreach($r as $k=>$v)
if ($m = range_merge($g, $v))
{
$g = $m;
unset($r[$k]); // we merged this value away
}
array_push($t, $g);
}
return($t);
}
?>