通过递归函数创建结构化数组

时间:2012-05-24 11:43:46

标签: php mysql sql arrays recursion

我有一张桌子

enter image description here

我想要递归显示如下图片

enter image description here

我在php中使用递归函数

function  reccall($cat_id)
 {
   global $no,$recArray;
   $sql = "SELECT a.*
      FROM cat_master   
           WHERE 
        parent_id = $cat_id 
      ORDER BY 
        id ASC
      ";
         $result = mysql_query($sql) or die("Could not fetech Recursively");
    while($row = mysql_fetch_object($result))
    {
      $recArray[$no]['value'] = mysql_real_escape_string($row->value);
      $recArray[$no]['id'] = $row->id;
       ++$no;
      reccall($row->id);
    }
    return $recArray;    
 } 

但是我无法生成结构化数组,就像订单不是图片一样。一直创建一个简单的数组。任何人都可以帮我创建结构化数组,就像上面显示的顺序一样。

2 个答案:

答案 0 :(得分:1)

<?
// I identified this function separately because it is performed only once, for preparing data
// It's collect an array of all parents in the correct order for each id
function dest($array) {
    foreach($array as $key=>$value) {
        if($value['pid']==0) continue;

        $pid = $key;
        $array[$key]['dest'] = array();
        while ( $pid = $array[$pid]['pid'] ) {
            if($key == $pid) exit("this tree is broken");
            $array[$key]['dest'][] = $pid;
        }
    }

    return $array;
}
// Recursive function that puts the items in the correct tree. removes the parameter dest.
function tree($array) {
    foreach($array as $key=>$value) {
        if( is_array($value['dest']) && !empty($value['dest']) ) {
            $pid = array_pop($value['dest']);
            if( empty($value['dest']) ) unset($value['dest']);

            $array[$pid]['childrens'][$key] = $value;
            $array[$pid]['childrens'] = tree($array[$pid]['childrens']);
            unset($array[$key]);
        }
    }

    return $array;
}

$array = array(
    1 => array(
        'title'=>'q',
        'pid'=>0,
        ),
    2 => array(
        'title'=>'w',
        'pid'=>1,
        ),
    3 => array(
        'title'=>'e',
        'pid'=>0,
        ),
    4 => array(
        'title'=>'r',
        'pid'=>2,
        ),
    5 => array(
        'title'=>'t',
        'pid'=>1,
        ),
);

$tree = tree( dest($array) );

echo '<pre>';
print_r($array);
print_r($tree);
?>

顺便说一下,我应该注意这些数组并不是很有用。最好使用函数dest()的结果。

答案 1 :(得分:1)

使用此功能代替您的功能,我希望

解决您的问题
function reccall($cat_id)
 {
     $sql = "SELECT a.*
      FROM cat_master   
           WHERE 
        parent_id = $cat_id 
      ORDER BY 
        id ASC
      ";
         $result = mysql_query($sql) or die("Could not fetech Recursively");
    while($row = mysql_fetch_object($result))
    {
      $recArray[$no]['main']['value'] = mysql_real_escape_string($row->value);
      $recArray[$no]['main']['id'] = $row->id;         
      $recArray[$no]['child'] = reccall($row->id);
       ++$no;
    }
    return $recArray;    
 }