排序步骤和子步骤

I have an application that needs to be able to get procedures from a database and display the steps in the correct order. Sometimes, steps have substeps, and other times, those substeps can have substeps of their own. It's not an option for me to write a separate html page for each procedure, since we're talking about quite a lot of them. I intend to generate the view on the fly. Here is a sample of what I would be displaying:

1. Step 1
  a. Step 1a
    i. Step 1ai
    ii. Step 1aii
  b. Step 1b
2. Step 2

As it currently stands, I have a PROCEDURE table, a STEP table, and a PROCEDURE_STEP table to cross reference them. The STEP table has a substep_of field, which is a foreign key to the id of the parent step. I'm still at the stage where I can modify the database as needed.

My question then, is after I do this:

mysql_query(SELECT * FROM PROCEDURE_STEP WHERE procedure_id = $id);

How do I sort them so that each substep is neatly placed in the return array in order under its parent step? I'm going to send the return array to the view as a json encoded array, if that makes a difference.

You would probably want to do something like:

SELECT s.id, s.substep_of AS parent
FROM STEP s, PROCEDURE_STEP ps
WHERE ps.step_id = s.id
AND ps.procedure_id = $id;

This would get you a list of steps, each containing an id and a parent id. From this, you can build a tree recursively :)...

function get_children_of( $id, $steps ) {
    $children = array();

    foreach( $steps as $step )
        if( $step->parent == $id ) 
            $children[$step->id] = get_children_of( $step->id, $steps );

    // Make it null... so we don't have deal with empty arrays
    if( empty( $children ) ) $children = null; 

    return $children;            
}

$steps = run_crazy_mysql_query();
$tree = get_children_of( 0, $steps );

This should give you a tree that looks like:

0 => array(
    1 => null,
    2 => array(
        3 => null,
        4 => null
    )
)

That should give you something you can work with relatively easily to generate HTML lists of steps.