Conditional loop for category

$categories = get_categories( array(
    'parent' => 0,
) );

foreach ( $categories as $category ) {
    echo $category->name;
    $posts = get_posts( array(
        'category_name'  => $category->slug,
        'posts_per_page' => 3,
    ) );
    foreach ( $posts as $item ) {
        echo get_the_title( $item->ID );
    }
}

Something like this print wich you need. But it is very simple example.