Loading taxonomy terms in a tree in Drupal 8 I have multiple level of vocabulary, I want to display all level in the hierarchy same as taxonomy display. My taxonomy is like.

All
   Drinks
      Alcohol Drinks
         Beer
         Vodka
      Alcohol Free Drinks
         Coca Cola
         Pepsi
   Fruits
      Fruits For Losing Weight
         Watermelon
         Blackberrie
      Fruits For Dogs
         Strawberry
         Orange


now I am trying to load this using code.

$vid = 'food';
    $terms =\Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;loadTree($vid, 0, 1, FALSE);
    foreach ($terms as $term) {
        $term_data_1[$term-&gt;tid] = $term-&gt;name;
            $terms_2 =\Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;loadTree($vid, $term-&gt;tid, 1, FALSE);
            foreach ($terms_2 as $term_2) {
                $term_data_2[$term_2-&gt;tid] = $term_2-&gt;name;
                    $terms_3 =\Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;loadTree($vid, $term_2-&gt;tid, 1, FALSE);
                    foreach ($terms_3 as $term_3) {
                        $term_data_3[$term_3-&gt;tid] = $term_3-&gt;name;
                    }

            }
            $term_data_1[$term_2-&gt;tid] = $term_data_2;
            $term_data_1[$term_3-&gt;tid] = $term_data_3;
    }

    kint($term_data_1);


and this code giving result like



Need help to get term in hierarchy.
TermForm.php has an example of how to do this.

Basically you loop through the tree and add dashes according to the depth of the term.

Here's an example you can use:

$options = [];
foreach (\Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;loadTree($vid) as $item) {
  $options[$item-&gt;tid] = str_repeat('-', $item-&gt;depth) . $item-&gt;name;
}


UPDATE: If you want a nested array of terms, you can do like this:

$result = [];
foreach (\Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;loadTree($vid) as $item) {
  $parents = array_reverse(\Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;loadAllParents($item-&gt;tid), TRUE);
  $r = &amp;$result;
  foreach ($parents as $k =&gt; $v) {
    if (isset($r[$k])) {
      $r[$k] = array_replace($r[$k], [$k =&gt; $v-&gt;label()]);
    }
    else {
      $r[$k] = [$k =&gt; $v-&gt;label()];
    }
    $r = &amp;$r[$k];
  }
}


That will work regardless of how many levels your terms are nested.