Friday, April 19, 2013

PHP, calculate the common elements in arrays using array_intersect



If MySQL query is too complicated, we may  divide it into several queries. This happens
often when we have very complicated search criterion.We need to combine the query results.
For example the query result event_id is stored in array $include_by_type, and
$include_by_type[0] stores ( 1,3,4, 5)
$include_by_type[1] stores ( 2,3,5, 6)
$include_by_type[2] stores ( 3,4,5, 7)
Now we want to combine all these results, i.e. to get common elements (3,5),
below is the code to achieve this using PHP function  array_intersect
<?php
$include_by_type=array();
  $acount = count($include_by_type);
   $intersect = $include_by_type[0];
   $i = 1;
   while($i < $acount){
      $intersect = array_intersect($intersect,$include_by_type[$i]);
      $i++;
   }
}

?>

What happen if we want to combine the result and remove the duplication, such as
final result (1,2,3,4,5,6,7)? We can first use array_merge to merge array, then use
array_unique function to removes duplicate values from an array.
Code:
<?php
$include_by_type=array();
  $acount = count($include_by_type);
   $merge = $include_by_type[0];
   $i = 1;
   while($i < $acount){
      $merge = array_merge($merge,$include_by_type[$i]);
      $i++;
   }

   $result = array_unique($merge);
}

?>


No comments:

Post a Comment