A module I was writing needed a specific vocabulary with hierarchical terms. I wrote this function to save the terms:
<?php
/**
* Save recursive array of terms for a vocabulary.
*
* Example:
* <code><?php
* $terms = array(
* Species => array(
* Dog ,
* Cat ,
* Bird ),
* Sex => array(
* Male ,
* Female ) )
* _save_terms_recursive( $vid, $terms );
* </code>
*
* @param int $vid Vocabulary id
* @param array $terms Recursive array of terms
* @param int $ptid Parent term id (generated by taxonomy_save_term)
*/
function _save_terms_recursive( $vid, &$terms, $ptid=0 ) {
foreach ( $terms as $k => $v ) {
// simple check for numeric indices (term array without children)
$name = is_string( $k ) ? $k : $v;
$term = array( vid => $vid, name => $name, parent => $ptid );
taxonomy_save_term( $term );
if ( is_array( $v ) && count( $v ) )
_save_terms_recursive( $vid, $terms[ $k ], $term[ tid ] );
}
}