SitePoint Sponsor

User Tag List

Page 1 of 2 12 LastLast
Results 1 to 25 of 39
  1. #1
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    newbie: Accessing an Array of Objects

    Hello all,

    I'm storing some database information on a array of objects.
    If I print_r the returned results I get something link this:


    Array (
    [0] => stdClass Object ( [subcategoria] => Bla subcategoria] => subla1a
    [1] => stdClass Object ( [subcategoria] => Bla [subsubcategoria] => subla1b
    [2] => stdClass Object ( [subcategoria] => Bla [subsubcategoria] => subla1c
    [3] => stdClass Object ( [subcategoria] => Ble [subcategoria] => )
    [4] => stdClass Object ( [subcategoria] => Bli [subsubcategoria] => )
    )

    I want to use a foreach to loop over subcategoria values, but I'm having a hard time trying to find the right sintax to access those values.

    Can anyone help me find the right sintax?

  2. #2
    SitePoint Addict
    Join Date
    Dec 2004
    Posts
    240
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It would be a little bit simpler to give you an example if you could show some relevant code ...

    Basically, your objects are in an array, you could loop through the array using foreach. Each object has a property subcategoria. So it is accessed as $myobject->subcategoria. If I understand it correctly, this property contains an array, so you could use foreach on it again ...

    Probably I have not understood the question correctly ... Could you give more information in this case ?

  3. #3
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    I'm sure this will help you figure it all out. It looks as if this pertains to the same question.

    http://www.sitepoint.com/forums/show...10#post4369195

  4. #4
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by SKDevelopment View Post
    Probably I have not understood the question correctly ...
    I believe you have.

    Quote Originally Posted by SKDevelopment View Post
    Basically, your objects are in an array, you could loop through the array using foreach. Each object has a property subcategoria. So it is accessed as $myobject->subcategoria. If I understand it correctly, this property contains an array, so you could use foreach on it again ...
    Ok... If I do $myobject->subcategoria I get an error, telling me that I'm trying to access a no property (something like this). I know understand why. I'm getting an error because my subcategoria in fact isn't a property, however, $myobject->subcategoria[]; may work?
    I cannot test right now, but if I do $myobject->subcategoria[0] I will get some values returned?


    Quote Originally Posted by oddz View Post
    I'm sure this will help you figure it all out. It looks as if this pertains to the same question.
    http://www.sitepoint.com/forums/show...10#post4369195
    I will read it carefully.

    But, well... It's about the same problem, but is not the same intend.
    Here, the intend is to understand how can we enter inside this "thinks", aka, array of objects.

    Today will be for a filter link list, tomorrow for something else, but what I'd like to learn is: how can we properly access a value on an array of objects that as, inside, another array, and probably yet another array.... ?




    Regards,
    Márcio

  5. #5
    SitePoint Addict
    Join Date
    Dec 2004
    Posts
    240
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by oikram View Post
    Ok... If I do $myobject->subcategoria I get an error, telling me that I'm trying to access a no property (something like this). I know understand why. I'm getting an error because my subcategoria in fact isn't a property, however, $myobject->subcategoria[]; may work?
    I cannot test right now, but if I do $myobject->subcategoria[0] I will get some values returned?
    Could you post your code ? Just in case: Of course any logins/passwords (if any) must be replaced with "***" before posting ...

    I am sorry, but it is very difficult to answer without seeing the actual code.

  6. #6
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    On my model:

    PHP Code:
    function getSubCategorias($id_cat)
    {    
            
    $query $this->db->query("
            SELECT t2.nome_cat AS subcategoria, t3.nome_cat AS subsubcategoria
            FROM categoria AS t1
            LEFT JOIN categoria AS t2 ON t2.parent_id_cat = t1.id_cat
            LEFT JOIN categoria AS t3 ON t3.parent_id_cat = t2.id_cat
            WHERE t1.id_cat = '
    $id_cat'");
            
            return 
    $query->result();

    Note: the result() returns database results as objects. (similar to fetchObject I suppose.

    On my controller:
    PHP Code:
    $data['menucategorias'] = $this->M_Categoria->getSubCategorias($cat->id_cat); 
    On my view:
    Code:
    echo ($menucategorias->subcategoria[0]);
    I get:
    Notice: "Trying to get property of non-object."

    If I do print_r($menucategorias) I get this:
    PHP Code:
    Array ( [0] => stdClass Object ( [subcategoria] => Fitofármacos [subsubcategoria] => Herbicidas ) [1] => stdClass Object ( [subcategoria] => Fitofármacos [subsubcategoria] => Insecticidas ) [2] => stdClass Object ( [subcategoria] => Fitofármacos [subsubcategoria] => Fungicidas ) [3] => stdClass Object ( [subcategoria] => Adubos [subsubcategoria] => ) [4] => stdClass Object ( [subcategoria] => Sementes [subsubcategoria] => ) ) 


    Regards,
    Márcio

  7. #7
    SitePoint Addict
    Join Date
    Dec 2004
    Posts
    240
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    $menucategorias is an array with numerical indexes. It does not have properties. I think you meant
    PHP Code:
    echo ($menucategorias[0]->subcategoria); 
    Just in case: Also I hope $id_cat is not potential user input (e.g. it does not come from $_GET, $_POST or $_COOKIE) or it is properly validated before being used getSubCategorias(). getSubCategorias() does not contain any code for escaping or validation. If any user input is not validated properly and used in SQL queries, your code is in danger of SQL injection attack. Please see mysql_real_escape_string() for reference.

  8. #8
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks. Now I will re-read the print statement and try to understand.


    I will deal with security later on. My intend was just to learn how can I access this information.

    Again, thanks a lot.


    Regards,
    Márcio

  9. #9
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    I believe your model should look something like this:

    PHP Code:
    class CategoriesModel {

        public function 
    getSubCategorias($id_cat,$intDepth 2) {    
            
            
    $strSQL 'SELECT c.id_cat,c.nome_cat,c.parent_id_cat FROM categoria c';
            
    $arrQuery $this->db->query($strSQL);
            return 
    $this->_parseResultTree($id_cat,$arrQuery,intDepth);
        
        }
        
        private function 
    _parseResultTree($intParentId,&$arrRows,$intDepth=null,$intRunner=0) {
            
            
    // stop at this depth
            
    if($intDepth !== null && $intDepth == $intRunner) {
                return array();
            }
        
            
    $arrChildren = array();

            for(
    $i=0;$i<count($arrRows);$i++) {
                if(
    $intParentId == $arrRows[$i]['parent_id_cat']) {
                    
    $arrChildren array_merge($arrChildren,array_splice($arrRows,$i--,1));
                }
            }
        
            
    $intChildren count($arrChildren);
            if(
    $intChildren != 0) {
                for(
    $i=0;$i<$intChildren;$i++) {
                    
    $arrChildren[$i]['children'] = parse_into_tree($arrChildren[$i]['id_cat'],$arrRows,$intDepth,$intRunner++);
                }        
            }
        
            return 
    $arrChildren;
        
        }


    That way you have the flexibility to choose the number of depth. So if the depth is 1 no subcategories will appear. If the depth is 2 subcategories will appear but those items subcategories will not appear. Rather then pigeon holing yourself into a a specific depth. It also makes sense to include the formatting in the model because the tree represents the type of data you want back.

  10. #10
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Post

    Quote Originally Posted by oddz View Post
    I believe your model should look something like this:

    PHP Code:
    class CategoriesModel {

        public function 
    getSubCategorias($id_cat,$intDepth 2) {    
            
            
    $strSQL 'SELECT c.id_cat,c.nome_cat,c.parent_id_cat FROM categoria c';
            
    $arrQuery $this->db->query($strSQL);
            return 
    $this->_parseResultTree($id_cat,$arrQuery,intDepth);
        
        }
        
        private function 
    _parseResultTree($intParentId,&$arrRows,$intDepth=null,$intRunner=0) {
            
            
    // stop at this depth
            
    if($intDepth !== null && $intDepth == $intRunner) {
                return array();
            }
        
            
    $arrChildren = array();

            for(
    $i=0;$i<count($arrRows);$i++) {
                if(
    $intParentId == $arrRows[$i]['parent_id_cat']) {
                    
    $arrChildren array_merge($arrChildren,array_splice($arrRows,$i--,1));
                }
            }
        
            
    $intChildren count($arrChildren);
            if(
    $intChildren != 0) {
                for(
    $i=0;$i<$intChildren;$i++) {
                    
    $arrChildren[$i]['children'] = parse_into_tree($arrChildren[$i]['id_cat'],$arrRows,$intDepth,$intRunner++);
                }        
            }
        
            return 
    $arrChildren;
        
        }


    Thanks a trillion!
    Before I actually dig in and start asking questions about this code like a fool, I'd like to try understand the "all picture":

    Conceptually speaking:

    On the model:
    1)I will grab the database data and
    2)I will organize that data in some sort.

    On the controller:
    3) I will grab the number that is on my URI segment,
    and then
    4) call the method getSubCategorias and pass that retrieved id as $id_cat parameter.
    5) Then I will get the returned results, and put then on a $data array among other things, such us the page title, the main menu, that are on the same data array.
    6) I will use a method called load vars (I suppose it will grab all array keys, and make then variables available to be accessible over the views).
    7) I will load a view template on that $data array.

    On my view:
    Since according to step 6), each key of my $data array will have a corresponded variable available on the view:
    8) I will grab the variable responsible for holding the subcategories link and I will display the list with some logic:
    8.1) If the id that is on the URI segment does not match any id that is inside the categories, then, don't show the subcategories menu.
    If the id that is on the URI segment corresponds to any id that is inside subsubcategories, then, show subsubcategories (if they are not empty).




    Now with some code:
    The model as above.


    The controller:

    PHP Code:
    function seccao($id)
    {

        
    $cat $this->M_Categoria->getCategoria($id);
            
        
    $data['titulo'] = "As nossas soluções para ".$cat->nome_cat;
        
           
    //main menu rendering    
        
    $data['menuprincipal'] = $this->M_Categoria->getCategoriasPrincipais();
            
        
    //subcategories links:    
            
    $data['menucategorias'] = $this->M_Categoria->getSubCategorias($cat->id_cat);
            
    $data['main'] = 'v_categoria';
            
    $this->load->vars($data);

    $this->load->view('geral_tpl');



    The view:

    //my $data array key 'menucategorias' now is accessible by using the variable $menucategorias.

    PHP Code:
    function parse_into_menu($arrMenu,$strChildKey,$strNameKey,$intRunner=0) {
        
        
    $strNL "\n";
        
    $intMenu count($arrMenu);
        
        for(
    $i=0;$i<$intMenu;$i++) {
            if(
    $i==0) { 
                echo 
    str_repeat("\t",$intRunner),'<ul>',$strNL
            }
            
            if(!empty(
    $arrMenu[$i][$strChildKey])) {
                echo 
    str_repeat("\t",$intRunner+1),'<li>',$arrMenu[$i][$strNameKey],$strNL;
                
    parse_into_menu($arrMenu[$i][$strChildKey],$strChildKey,$strNameKey,$intRunner+2);
                echo 
    str_repeat("\t",$intRunner+1),'</li>',$strNL;
            } else {
                echo 
    str_repeat("\t",$intRunner+1),'<li>',$arrMenu[$i][$strNameKey],'</li>',$strNL;
            }
            
            if(
    $i==($intMenu-1)) { 
                echo 
    str_repeat("\t",$intRunner),'</ul>',$strNL
            }
        }
        


    //then I need a way to access parse_into_tree that was defined in the model, so that parse_into_menu could work...
    parse_into_menu(parse_into_tree(10,$menucategorias,'cats_id','parents_id','cats'),'cats','name'); 

    Ok... obliviously, this will not work, I'm just trying to connect some dots, in order to have all in one place to start digging. Would something more or less like this, make sense?

    ... please have patience...


    Regards,
    Márcio

  11. #11
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    The model is responsible for returning the data. Therefore, once the data has been loaded into the view you don't need to load it again. So placing a function with a similar purpose to _parseIntoTree() is redundant. Besides, the data will already be a tree when you fetch it from the model. That is the point of making it the responsibility of the model to format the data into a tree structure. This makes sense because that is the actual structure of the data not a flat result set but a tree.

    Now, you also need to add a method to the model for fetching a single category by by the primary key. This method will be called first by the controller to get the current category data. Once that is done you can pass that category primary key to the fetch for the menu on model. This way the method returns all items below the the current item or at the same level - depending on whether you pass the parent_id or id.

    In the view you then pass the menu data to parse_into_menu(). That will then build the HTML to display the menu.

  12. #12
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    So it would look something like this:

    Model
    PHP Code:
    class CategoriesModel {

        public function 
    getCategoria($id_cat) {
            
            
    $id_cat mysql_real_escape_string($id_cat); // escape data depending on connection 
            
    $strSQL 'SELECT c.id_cat,c.nome_cat,c.parent_id_cat FROM categoria c WHERE c.id_cat = '.$id_cat;
            return 
    $this->db->query($strSQL);
        
        }

        public function 
    getSubCategorias($id_cat,$intDepth=2) {    
            
            
    $strSQL 'SELECT c.id_cat,c.nome_cat,c.parent_id_cat FROM categoria c';
            
    $arrQuery $this->db->query($strSQL);
            return 
    $this->_parseResultTree($id_cat,$arrQuery,intDepth);
        
        }
        
        private function 
    _parseResultTree($intParentId,&$arrRows,$intDepth,$intRunner) {
            
            
    // stop at this depth
            
    if($intDepth == $intRunner) {
                return array();
            }
        
            
    $arrChildren = array();

            for(
    $i=0;$i<count($arrRows);$i++) {
                if(
    $intParentId == $arrRows[$i]['parent_id_cat']) {
                    
    $arrChildren array_merge($arrChildren,array_splice($arrRows,$i--,1));
                }
            }
        
            
    $intChildren count($arrChildren);
            if(
    $intChildren != 0) {
                for(
    $i=0;$i<$intChildren;$i++) {
                    
    $arrChildren[$i]['children'] = parse_into_tree($arrChildren[$i]['id_cat'],$arrRows,$intDepth,$intRunner++);
                }        
            }
        
            return 
    $arrChildren;
        
        }


    Contorller
    PHP Code:
    class ControllerName {
    function 
    seccao($id) {
        
        
    /*
        * Fetch category data from model
        */
        
    $cat $this->M_Categoria->getCategoria($id)

        
    /*
        * ?
        */   
        
    $data['menuprincipal'] = $this->M_Categoria->getCategoriasPrincipais();

        
    /*
        * Fetch category tree lower level categories - 2 levels 
        */
        
    $data['menucategorias'] = $this->M_Categoria->getSubCategorias($cat['id_cat'],2);
        
        
    /*
        * load data in template
        */
        
    $data['main'] = 'v_categoria';
        
    $data['titulo'] = "As nossas soluções para ".$cat['nome_cat'];
        
    $this->load->vars($data);
        
    $this->load->view('geral_tpl');



    You will also want to add some exception handling for a invalid category and no category - top level.

  13. #13
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok...

    I'm getting this error:

    Fatal error: Cannot use object of type stdClass as array in /home/akasite/private/application/controllers/c_categoria.php on line 22

    And the line 22 as:
    PHP Code:
    $data['menucategorias'] = $this->M_Categoria->getSubCategorias($cat['id_cat'],2); 
    I have changed to:
    PHP Code:
    $data['menucategorias'] = $this->M_Categoria->getSubCategorias($cat->id_cat,2); 
    Once this was done, I get other errors:


    A PHP Error was encountered
    Severity: Notice
    Message: Use of undefined constant intDepth - assumed 'intDepth'
    Filename: models/m_categoria.php
    Line Number: 64


    Here is the line number 64:
    PHP Code:
    return $this->_parseResultTree($id_cat,$arrQuery,intDepth); 
    I have changed to:
    PHP Code:
    return $this->_parseResultTree($id_cat,$arrQuery,$intDepth); 
    A PHP Error was encountered
    Severity: Warning
    Message: Missing argument 4 for M_Categoria::_parseResultTree(), called in /home/akasite/private/application/models/m_categoria.php on line 64 and defined
    Filename: models/m_categoria.php
    Line Number: 68


    And I have this on that line:
    PHP Code:
    private function _parseResultTree($intParentId,&$arrRows,$intDepth,$intRunner
    I have keep that line, and change the line 64 again to:
    PHP Code:
    return $this->_parseResultTree($id_cat,$arrQuery,$intDepth$intRunner); 

    A PHP Error was encountered
    Severity: Notice
    Message: Undefined variable: intRunner
    Filename: models/m_categoria.php
    Line Number: 72


    And here is the line 72:
    PHP Code:
    if($intDepth == $intRunner
    Unable to solve.



    And the worst of all, maybe the one that will end up this quest

    Fatal error: Cannot use object of type CI_DB_mysql_result as array in /home/akasite/private/application/models/m_categoria.php on line 81

    And on line 81 I have:
    PHP Code:
    if($intParentId == $arrRows[$i]['parent_id_cat']) { 
    Maybe this is a limitation on CodeIgniter framework?

    Regards,
    Márcio

  14. #14
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    I'm not incredibly familiar with CodeIgnitor. However, it seems as if Model::query returns objects rather then arrays for each row. If that is the case then wherever the result row is being treated as a array treat it as a object instead. So rather then $row['name'] use $row->name. That should fix that problem. The other problem is that $ is missing on some of the variables you mentioned. Take a look at the line numbers and place $ where it is missing. That is why those variables are being interpreted as constants.

  15. #15
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    private function _parseResultTree($intParentId,&$arrRows,$intDepth,$intRunner=0) {
    }

    $intRunner needs a default of 0.

  16. #16
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    comparison example (last issue)

    if($intParentId == $arrRows[$i]->parent_id_cat) {

  17. #17
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    should fix *most* issues:

    PHP Code:
    function seccao($id) {
        
        
    /*
        * Fetch category data from model
        */
        
    $cat $this->M_Categoria->getCategoria($id)

        
    /*
        * ?
        */   
        
    $data['menuprincipal'] = $this->M_Categoria->getCategoriasPrincipais();

        
    /*
        * Fetch category tree lower level categories - 2 levels 
        */
        
    $data['menucategorias'] = $this->M_Categoria->getSubCategorias($cat->id_cat,2);
        
        
    /*
        * load data in template
        */
        
    $data['main'] = 'v_categoria';
        
    $data['titulo'] = "As nossas soluções para ".$cat['nome_cat'];
        
    $this->load->vars($data);
        
    $this->load->view('geral_tpl');





    class 
    CategoriesModel {

        public function 
    getCategoria($id_cat) {
            
            
    $id_cat mysql_real_escape_string($id_cat); // escape data depending on connection 
            
    $strSQL 'SELECT c.id_cat,c.nome_cat,c.parent_id_cat FROM categoria c WHERE c.id_cat = '.$id_cat;
            return 
    $this->db->query($strSQL);
        
        }

        public function 
    getSubCategorias($id_cat,$intDepth=2) {    
            
            
    $strSQL 'SELECT c.id_cat,c.nome_cat,c.parent_id_cat FROM categoria c';
            
    $arrQuery $this->db->query($strSQL);
            return 
    $this->_parseResultTree($id_cat,$arrQuery,$intDepth);
        
        }
        
        private function 
    _parseResultTree($intParentId,&$arrRows,$intDepth,$intRunner=0) {
            
            
    // stop at this depth
            
    if($intDepth !== null && $intDepth == $intRunner) {
                return array();
            }
        
            
    $arrChildren = array();

            for(
    $i=0;$i<count($arrRows);$i++) {
                if(
    $intParentId == $arrRows[$i]->parent_id_cat) {
                    
    $arrChildren array_merge($arrChildren,array_splice($arrRows,$i--,1));
                }
            }
        
            
    $intChildren count($arrChildren);
            if(
    $intChildren != 0) {
                for(
    $i=0;$i<$intChildren;$i++) {
                    
    $arrChildren[$i]->children parse_into_tree($arrChildren[$i]->id_cat,$arrRows,$intDepth,$intRunner++);
                }        
            }
        
            return 
    $arrChildren;
        
        }



  18. #18
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks a lot Oddz. Sorry for not replying. I was afk. :s
    I will give it try tonight and I hope I can put a nice view file for consideration.

    Regards,
    Márcio

  19. #19
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok... sorry for this late reply, I was trying to solve this on CI forums.

    I'm having the same error as before:
    Fatal error: Cannot use object of type CI_DB_mysql_result as array in /home/akasite/private/application/models/m_categoria.php on line 81


    The line:
    PHP Code:
    if($intParentId == $arrRows[$i]->parent_id_cat) { 
    I've trying to get some help on CI forums, but since this code isn't mine, and I can't understand it YET in is full glory, I'm getting a hard time to solve it.

    Some advices were:
    1)
    store the returning database result on a variable, and make a comparison of one return element. for example:
    PHP Code:
    if ($query->num_rows() > 0){


    Others have said:
    2)
    It's not in the if... look at the code that is creating $arrRows
    On my very limited understanding of the code:
    we are putting our query on a variable, so 1) may not solve and,
    there's no other place, before the line that get's the error, where $arrRows is treated as an array. So 2) seems to not solve either.

    Does those two comments from CI side of things, brings any new lights to you?


    Thanks oddz,

    Márcio

  20. #20
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    ok...
    Codeigniter query() returns an OBJECT.
    We can use this function result_array() to return an array.

    Hoping that this will work, I've changed to:

    PHP Code:
    public function getSubCategorias($id_cat,$intDepth=2
        {    
            
            
    $strSQL 'SELECT c.id_cat,c.nome_cat,c.parent_id_cat FROM categoria c';
            
    $query $this->db->query($strSQL);
            
            
    $arrQuery $query->result_array();
            
            return 
    $this->_parseResultTree($id_cat,$arrQuery,$intDepth$intRunner=0);
            
        } 
    Now, I hope $arrQuery is an array, and that I could use the code.

    However, I'm getting the following:

    Inside the method _parseResultTree:

    I have this:
    PHP Code:
    $arrChildren[$i]['children'] = parse_into_tree($arrChildren[$i]['id_cat'],$arrRows,$intDepth,$intRunner++); 
    But I have any parse_into_tree function in there ...

    UPDATE: I've also tried to use: _parseResultTree as well. Same undefined error.

    Any help?

    Thanks,
    M&#225;rcio

  21. #21
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    $arrChildren[$i]['children'] = $this->_parseResultTree($arrChildren[$i]['id_cat'],$arrRows,$intDepth,$intRunner++);

  22. #22
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks.

    We use $this-> because we are calling a class method right?
    However, it seems weird to me, that we call the method inside the method.
    Is this what we call recursion?

    I will give it a read...


    Thanks again,
    Márcio

  23. #23
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2006
    Location
    Augusta, Georgia, United States
    Posts
    4,194
    Mentioned
    17 Post(s)
    Tagged
    5 Thread(s)
    Yes, building that tree requires recursion.

  24. #24
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, I'm really sorry, but I'm unable to solve this alone.

    We have an output like this now:

    Array (
    [0] => Array (
    [id_cat] => 6
    [nome_cat] => Fitofármacos
    [parent_id_cat] => 1
    [children] => Array (
    [0] => Array (
    [id_cat] => 9
    [nome_cat] => Herbicidas
    [parent_id_cat] => 6
    [children] => Array ( ) )

    [1] => Array (
    [id_cat] => 10
    [nome_cat] => Insecticidas
    [parent_id_cat] => 6
    [children] => Array ( ) )

    [2] => Array (
    [id_cat] => 11
    [nome_cat] => Fungicidas
    [parent_id_cat] => 6
    [children] => Array ( )
    )
    )
    )

    [1] => Array (
    [id_cat] => 7
    [nome_cat] => Adubos
    [parent_id_cat] => 1
    [children] => Array ( )
    )
    [2] => Array (
    [id_cat] => 8
    [nome_cat] => Sementes
    [parent_id_cat] => 1
    [children] => Array ( )
    )
    )

    I understand that if we do something like this:
    PHP Code:
    for($i=0;$i<count($menucategorias);$i++) 
            {
                
                if (
    $menucategorias[$i] > 0)
                {
                    echo 
    "<li>";
                    echo 
    anchor("c_categoria/seccao/".$menucategorias[$i]['id_cat'], $menucategorias[$i]['nome_cat']);
                    echo 
    "</li>"
                }
            }
            echo 
    "</ul>"
    We will get the subcategories. and if we click on one of those subcategories we will get the sub-subcategories listed as well. However, I can't never show both on the same page.

    Page1:
    subcat1
    subcat2
    subcat3

    and when we click on any of those, we will get, page2:
    sub-subcat1
    sub-subcat2
    ... etc...

    Here's an example:
    http://www.nuvemk.com/c_categoria/seccao/1


    But the intended result was to show, when we click on one of the subcat links, if they have a childcat, then, show the childcat, AS WELL.
    So that we end up with something like this:

    Page2:
    subcat1 - sub-subcat1
    subcat2 - sub-subcat2
    subcat3

    How can we deal with the iteration in order to allow the display of both?

    Stupid try:
    PHP Code:
    echo "<ul>";
            
    //Se houver sub-categorias:
            
    for($i=0;$i<count($menucategorias);$i++) 
            {
                for(
    $j=0$j<count($menucategorias[$i]); $j++)
                {
                    if (
    $menucategorias[$i] > 0)
                    {
                        echo 
    "<li>";
                        echo 
    anchor("c_categoria/seccao/".$menucategorias[$i]['id_cat'], $menucategorias[$i]['nome_cat']);
                        echo 
    "</li>";
                    }
                    
                    if (
    $menucategorias[$j]>0)
                    {
                        echo 
    "<li>";
                        echo 
    anchor("c_categoria/seccao/".$menucategorias[$i][$j]['id_cat'], $menucategorias[$i][$j]['nome_cat']);
                        echo 
    "</li>"
                    }
                }
            }
            echo 
    "</ul>"
    ps- I have tried to look at your loop posted above and I've tried to translate that, in order to use it on this scenario, but I couldn't do it. To many pending questions and very complicated for me. :s



    Regards,
    Márcio

  25. #25
    SitePoint Wizard
    Join Date
    Feb 2009
    Posts
    1,006
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This one makes more sense, I believe...

    I can access a sub-subcategory value like this:
    PHP Code:
    echo $menucategorias[0]['children'][0]['nome_cat']; 
    So I have tried to do it like this:
    PHP Code:
    $menucategorias[$i]['children'][$j]['parent_id_cat'
    But I'm getting this error:
    Message: Undefined offset: 3


    The full code:
    PHP Code:
    echo "<ul>";

            for(
    $i=0;$i<count($menucategorias);$i++) 
            {
                
                if (
    $menucategorias[$i] > 0)
                {
                    echo 
    "<li>";
                    echo 
    anchor("c_categoria/seccao/".$menucategorias[$i]['id_cat'], $menucategorias[$i]['nome_cat']);
                    echo 
    "</li>"
                }
                
                for (
    $j=0;$j<count($menucategorias[$i]);$j++) 
                {
                    if (
    $menucategorias[$i]['children'][$j]['parent_id_cat']==$this->uri->segment(3))
                    {
                        echo 
    "<li>";
                        echo 
    anchor("c_categoria/seccao/".$menucategorias[$i]['children'][$j]['id_cat'], $menucategorias[$i]['nome_cat'][$j]['nome_cat']);
                        echo 
    "</li>";
                    }
                }
                
            }
            echo 
    "</ul>"
    Dying,
    Márcio


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •