Accessing taxonomy's name and parent TID in Drupal 8

You are here

This function allows you to access a taxonomy entity fields and get the following results. The child's parents TID, the TID, and the field's string name of the TID being requested.  The results are placed into an array and custom keys can be used when being iterated over.

It works in Drupal 8 but I have access the fields using name spacing and avoided depreciated Drupal 8 functions and methods so it should be future proofed for Drupal 9 

 * @param $taxonomyTermArr
 * @return array
function _taxonomy_tid_and_taxonomy_terms_parents_on_entity($taxonomyFieldArr) {
  //-- Get tid number and parent tid number
  $arrayResult = array();
  foreach ($taxonomyTermArr as $taxonomyTid) {
    $term = \Drupal\taxonomy\Entity\Term::load($taxonomyTid);
    $storage = \Drupal::service('entity_type.manager')
    $parents = $storage->loadParents($term->id());
    $termName = $term->id();
    $arrayResult[$termName]['parent_tid'] = array_keys($parents);
    $arrayResult[$termName]['tid'] = $term->id();
    $arrayResult[$termName]['name'] = $term->getName();


  return $arrayResult;