Version: 1.0
Type: Function
Category: Shopping Carts
License: GNU General Public License
Description: This code will help you to make those “Customers who bought this also bought” lists, based on the times that 2 items have been seen together.
<? /* This code will help you to make those "Customers who bought this also bought" lists, based on the times that 2 items have been seen together. Every time a user/customer select/buys something you have to call 'setRel' with an array of the selected items ids as the parameter. For example, if the user buys the items 'a','b','c' you have to call setRel like this: <? $items=array('a','b','c'); setRel($items); ?> Then, when you want to display the top 2 items related to the item 'b' you do: <? $items=getRels('b',2); print "Customers who like this also like:"; foreach($items as $item){ print " $item"; } //this will print: // Customers who like this also like: a c ?> This code uses MySQL, but can be easily ported to other DBs. You have to create a table in your database, called 'relsel'. you can cut'n paste this commands (for MySQL): CREATE TABLE relsel ( id1 varchar(40) DEFAULT '' NOT NULL, id2 varchar(40) DEFAULT '' NOT NULL, times int(11), PRIMARY KEY (id1,id2) ); If you 're using integer ids to identify your items, you may change id1 and id2 to be int instead of varchar. You have to connect to your DB before calling this functions. ;) Martin Sarsale [email protected] */ /* mysql_connect("localhost",'root','XXXXX'); mysql_select_db("test"); */ function setRel($items){ // setRel sets the relationship between all the // elements in the array $items while($item=array_pop($items)){ foreach ($items as $each){ if ($item == $each){continue;} $pair=array($item,$each); sort($pair); list($i1,$i2)=$pair; list($times)=mysql_fetch_row(mysql_query("select times from relsel where id1='$i1' and id2='$i2'")); $times++; mysql_query("replace relsel set id1='$i1',id2='$i2',times='$times'"); } } } function getRels($id,$max=3){ // gets $max items related to $id $rels=array(); $q=mysql_query("select id1,id2 from relsel where id1='$id' or id2='$id' order by times desc limit $max"); while(list($i1,$i2)=mysql_fetch_row($q)){ $rels[]= ($i1==$id) ? $i2 : $i1; } return $rels; } ?>