note 66347 rejected from function.array-intersect by bjori
| From: | bjori@php.net | Date: | Fri, 19 May 2006 16:38:32 +0000 |
| Subject: | note 66347 rejected from function.array-intersect by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-111695@lists.php.net to get a copy of this message | ||
Note Submitter: andredejong at student dot ru dot nl
----
array_intersect performs badly on intersecting large datasets (>100 values).
the following function is faster for large arrays;
<?
function _array_intersect(&$ar ,$doneList = NULL,$size = NULL){
$smallest = 0;
$largest = 0;
$min = -1;
$max = 0;
// the intersection of 1 array is itself
if (count($ar) == 1){
return($ar[0]);
}
// search smallest and largest array
for ($i=0;$i < count($ar);$i++){
if (is_array($doneList) && in_array($i,$doneList)){ // items in donelist are already
processed
continue;
}
if (!isset($size[$i])){
$size[$i] = count($ar[$i]); // cache the count operation (better performance in
large datasets)
}
// determine minimum
if($size[$i] < $min || $min == -1){
$min = $size[$i];
$smallest = $i;
}
// determine maximum
if (($size[$i] >= $max)){
$max = $size[$i];
$largest = $i;
}
}
// flip keys of largest array
$trans = array_flip($ar[$largest]);
// do the comparison
$output = array();
foreach($ar[$smallest] as $value){
if (isset($trans[$value])){
$output[] = $value;
}
}
$doneList[] = $largest;
$doneList[] = $smallest;
// do a recursive call for moredimensional arrays
if ((count($ar)) > count($doneList)){
$index = count($ar);
$ar[] = $output;
$output = _array_intersect($ar,$doneList,$size);
unset($ar[$index]);
}
return $output;
}
?>
Equivalence:
<? $result = _array_intersect($array); ?>
is equivalent to :
<?
foreach($_array as $subSet){
$array[] = array_unique($subSet);
}
$result = call_user_func_array('array_intersect',$array);
?>