I came up with another code that doesn't use recursivity:
<?php
//Let's say the DB returns:
$categories = array(
    array( 'id' => 1, 'name' => 'Category 1', 'parent' => null ),
    array( 'id' => 2, 'name' => 'Category 2', 'parent' => null ),
    array( 'id' => 3, 'name' => 'Category 3', 'parent' => 1 ),
    array( 'id' => 4, 'name' => 'Category 4', 'parent' => 3)
    );
$sortedCategories = assignChildren( $categories );
function assignChildren( &$categories )
{
    $sortedCategories = array();
    foreach( $categories as &$category )
    {
        if ( !isset( $category['children'] ) )
        {
            // set the children
            $category['children'] = array();
            foreach( $categories as &$subcategory )
            {
                if( $category['id'] == $subcategory['parent'] )
                {
                    $category['children'][] = &$subcategory;
                }
            }
        }
        if ( is_null( $category['parent'] ) )
        {
            $sortedCategories[] = &$category;
        }
    }
    return $sortedCategories;
}
var_dump( $sortedCategories );
Outputs:
array(2) {
  [0]=>
  &array(4) {
    ["id"]=>
    int(1)
    ["name"]=>
    string(10) "Category 1"
    ["parent"]=>
    NULL
    ["children"]=>
    array(1) {
      [0]=>
      &array(4) {
        ["id"]=>
        int(3)
        ["name"]=>
        string(10) "Category 3"
        ["parent"]=>
        int(1)
        ["children"]=>
        array(1) {
          [0]=>
          &array(4) {
            ["id"]=>
            int(4)
            ["name"]=>
            string(10) "Category 4"
            ["parent"]=>
            int(3)
            ["children"]=>
            array(0) {
            }
          }
        }
      }
    }
  }
  [1]=>
  &array(4) {
    ["id"]=>
    int(2)
    ["name"]=>
    string(10) "Category 2"
    ["parent"]=>
    NULL
    ["children"]=>
    array(0) {
    }
  }
}