Steph68
Steph68

Reputation: 19

Codeigniter multi-dimensional array return only the first row

One day I'm on this problem and I cant find the solution. My goal is to return a list of links from an ID (the father). So I want all his childs. But in the view, I only have on result (the 1st one...).

I have in my controller :

$data['list_link'] = $this->menuManager->list_link();

In my Model :

function list_link($fatherid=0){
    $r = array();
    $sSQL = 'SELECT * FROM categories WHERE fatherid = ' . $fatherid . ' AND siteid = ' . MY_SITEID_DEFAULT . ' ORDER BY name';
    $query = $this->db->query($sSQL);
    // stock results in array
    $r[] = $query->result_array();
    foreach ($query->result() as $row) {
        // let's find the childs
        $this->list_link($row->id,$loop);
    }
    return $r;
}

If I "for each" the $r here, all looks good. So, $data['list_link'] shoud now have all the rows.

In my view :

 foreach ($list_link as $link){
   foreach ($link as $row){
      echo $row['name'];
   }
}

But, I only have the first links (first childs), not the other one. Any help would be greatly appreciated as I'm on that problem for days...

Upvotes: 2

Views: 934

Answers (1)

Shomz
Shomz

Reputation: 37701

You're not storing any values in the recursive calls (though I'm still not sure you'd get what you expect). You'd need to populate $r with each function call:

$r[] = $this->list_link($row->id,$loop);

However, either I missed something or you're overcomplicating things, but I think you could simply return the result array and use it:

function list_link($fatherid=0,$loop=0){
    $sSQL = 'SELECT * FROM categories WHERE fatherid = ' . $fatherid . ' AND siteid = ' . MY_SITEID_DEFAULT . ' ORDER BY name';
    $query = $this->db->query($sSQL);
    return $query->result_array();
}

UPDATE

Your latest version still doesn't collect the data from recursive calls, here is the full function, see if it works:

function list_link($fatherid=0){
    $r = array();
    $sSQL = 'SELECT * FROM categories WHERE fatherid = ' . $fatherid . ' AND siteid = ' . MY_SITEID_DEFAULT . ' ORDER BY name';
    $query = $this->db->query($sSQL);
    $result = $query->result_array();
    // stock results in array
    $r[$fatherid] = $result;
    foreach ($result as $row) {
        // let's find the children
        $r[$fatherid][$row['id']] = $this->list_link($row['id']);
    }
    return $r;
}

Note that I've added $r[$fatherid][$row['id']] so the end result should be an array with a branching structure. If you don't want that, just do $r[] instead.

Upvotes: 1

Related Questions