开发者

array of dictionaries is cast to array of objects in a recursive function in codeigniter

I've noticed some very strange behaviour today in Code Igniter. I have this locations table in my database which has the columns id,name,id_parent,level (it's a tree of locations) and i've tried to generate an array of locations sorted depth first. My approach was to build a recursive function in a helper file:

$CI = & get_instance();
$CI->load->database();

function dfs_locations($node, $level){
    global $CI;
    $result = array();
    $result[] = array('id'=>$node,'level'=>$level);
    $q = $CI->db->query(
        'select l1.id from locations l1, locations l2'.
        ' where l1.id_parent=l2.id and l2.id='.$node.' order by l1.id'
    );
    foreach ($q->result() as $row){
        $result[] = json_decode(dfs_locations($row->id,$level+1));
    }
    return json_encode($result);
}

The result is a bit strange. Printing json_decode(dfs_locations($root_id,1)) yields"

Array
(
[0] => Array
(
[0] => stdClass Object
(
[id] => 1
[nivel] => 1
)

[1] => Array
(
[0] => stdClass Object
(
[id] =>开发者_高级运维; 2
[nivel] => 2
)

and so on.Without json encoding/decoding i get even stranger results and only the root gets printed. Any help is greatly appreciated. Thank you.


Sorted out. Still don't know why this craziness happens. Here's how I've rewrote the function:

function dfs_locations($node, $level)
{   global $CI;
    $result = array();
    $result[] = array('id'=>$node,'level'=>$level);
    $q = $CI->db->query(
        'select l1.id from locations l1, locations l2'.
        ' where l1.id_parent=l2.id and l2.id='.$node.' order by l1.id'
    );
    foreach ($q->result() as $row)
    {   $array = dfs_locations($row->id,$level+1);
        foreach($array as $piece)
            $result[] = array('id'=>$piece['id'],'level'=>$piece['nivel']);
    }
    return $result;
}

Notice that i take the array returned by the recursive function, iterate through it and add its elements to the currently visible array (i don't like how inefficient it is but it gets the job done). One more thing is required, when calling for more then one root:

$all_locations = array();
foreach($roots as $root)
{   $auxiliary = dfs_locations($root,1);
    foreach($auxiliary as $result) 
        $all_locations[] = $result;
}

Even though there's just one result i can't do $locations[] = $auxiliary[0] or even $locations[] = dfs_locations($root,1)[0], which is a shame; Here's how the final array looks like:

Array
(
[0] => Array
(
[id] => 1
[nivel] => 1
)

[1] => Array
(
[id] => 2
[nivel] => 2
)

[2] => Array
(
[id] => 7
[nivel] => 3
)

[3] => Array
(
[id] => 91
[nivel] => 4
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜