Professional CodeIgniter

(singke) #1

Chapter 4: Creating the Main Web Site


79


The final output of the getAllCategories() function is a multidimensional array. Here ’ s a snippet
from that array as seen through the print_r() function, so you can visualize the discussion:


[0] = > Array
(
[id] = > 1
[name] = > shoes
[shortdesc] = >
[longdesc] = >
[status] = > active
[parentid] = > 0
)

[1] = > Array
(
[id] = > 2
[name] = > shirts
[shortdesc] = >
[longdesc] = >
[status] = > active
[parentid] = > 0
)

[2] = > Array
(
[id] = > 3
[name] = > pants
[shortdesc] = >
[longdesc] = >
[status] = > active
[parentid] = > 0
)

Unfortunately, the view itself is looking for a flat array, with a key that corresponds to the category ID
and a value that corresponds to the category name.

There are three possible solutions to this problem. The first is to rewrite the view to handle a
multidimensional array. The second is to rewrite the model function to output the array as a flat list. The
third is to create a different model function for your navigation and use that instead.

Of all the options, the third makes the most sense. Think about it: Why send the view more data than it
needs? Why shouldn ’ t you hand the view just what it needs, in a concise, neat package? Another thing to
think about: Is it possible you may need the getAllCategories() function at some point? Of course!
So it ’ s good to keep it.


Go ahead and create a new model function called getCategoriesNav(). This new function will be
dedicated solely to extracting category data needed for the navigation:


function getCategoriesNav(){
$data = array();
$Q = $this- > db- > get(‘categories’);
if ($Q- > num_rows() > 0){
Free download pdf