php递归测试实例1

根据分类父id 递归查询父类别   结果放入二维数组中

//$db 为一个数据库对象

function get_array($pid,$db){ 
  global $category;
  $sql = " select * from yl_category where id = " . $pid;
  $res = $db->query($sql); //查询返回所有结果
  if (! empty($res)) {
    $category[] = $res[0];
    return get_array($res[0]['pid'],$db);
  }else {
    return $category;
  }
}

if (! empty($pid)) {
$category = get_array($pid,$db);	
}
$category = array_reverse($category);  //反转数组
echo '<pre>';
print_r($category);exit;

返回结果

Array
(
    [0] => Array
        (
            [id] => 1
            [category_name] => 22223331
            [pid] => 0
            [orders] => 1
        )

    [1] => Array
        (
            [id] => 2
            [category_name] => 2222111
            [pid] => 1
            [orders] => 1
        )

    [2] => Array
        (
            [id] => 11
            [category_name] => 333
            [pid] => 2
            [orders] => 0
        )

)

  

 

 

posted @ 2013-05-21 10:08  河边的老牛  阅读(167)  评论(0编辑  收藏  举报