Professional CodeIgniter

(singke) #1

Chapter 4: Creating the Main Web Site


83


Retrieving Random Products for the Sidebar


The second function, getRandomProducts() , builds on the first function. It retrieves a variable number
of products (you can pass in the number as an argument) from different categories (one per category, in
fact). It also skips whatever product you tell it to skip, as you will pass in the product ID that was
retrieved by the getMainFeature() function.

Have a look at the function, and then move on to the discussion below.

function getRandomProducts($limit,$skip){
$data = array();
$temp = array();
if ($limit == 0){
$limit=3;
}
$this- > db- > select(“id,name,thumbnail,category_id”);
$this- > db- > where(‘id !=’, $skip);
$this- > db- > where(‘status’, ‘active’);
$this- > db- > orderby(“category_id”,”asc”);
$this- > db- > limit(100);
$Q = $this- > db- > get(‘products’);
if ($Q- > num_rows() > 0){
foreach ($Q- > result_array() as $row){
$temp[$row[‘category_id’]] = array(
“id” = > $row[‘id’],
“name” = > $row[‘name’],
“thumbnail” = > $row[‘thumbnail’]
);
}
}

shuffle($temp);
if (count($temp)){
for ($i=1;$i < =$limit;$i++){
$data[] = array_shift($temp);
}
}

$Q- > free_result();
return $data;
}

This function retrieves a maximum of 100 records, selecting fields like ID, name, thumbnail, and
category_id, and places these data in a temporary array that is later shuffled (to ensure randomness;
otherwise, the same categories are likely to be processed repeatedly) and then further processed by a
simple for loop that creates a final data array.
Free download pdf