Programmatically assign a node to an organic group How can I programmatically assign a node to an organic group?

I have tried the followings and non of them worked (assuming $target_group is the group ID that I want the $node to be assigned to):

$node-&gt;og_groups = array($target_group =&gt; $target_group);
node_save($node);


,

$group = node_load($target_group);
$node-&gt;og_groups[0] = $target_group;
$node-&gt;og_groups_names[0] = $group-&gt;title;


What is the proper way to do this?
Assuming Drupal 7, you want to use the og_group function in the API

/**
 * Set an association (e.g. subscribe) an entity to a group.
 *
 * @param $gid
 *   The group ID.
 * @param $values
 *   Array with the information to pass along, until it is processed in
 *   og_entity_presave(). Keys are:
 *   - "entity type": Optional; The entity type (e.g. "node" or "user").
 *     Defaults to 'user'
 *   - "entity" :Optional; The entity to set the association. Defaults to the
 *     current user if the $entity_type property is set to 'user'.
 *   - "state": Optional; The state of the association. Can be:
 *     - OG_STATE_ACTIVE
 *     - OG_STATE_PENDING
 *     - OG_STATE_BLOCKED
 *   - "save": Optional; TRUE if fields value should be saved. Defaults to TRUE.
 *   - "force reload": Optional; Determine if og_load_entity() should be used on
 *     the passed entity. This can be used when you pass an entity that has been
 *     saved yet to the database, but you want to assign it groups. Defaults to TRUE.
 *     // TODO: Adds docs on rest of keys.
 *
 * @return
 *   The entity with the fields updated.
 */
function og_group($gid, $values = array()) { ...


For your code, this would look like:

$values = array('entity type' =&gt; 'node', 'entity' =&gt; $node, 'state' =&gt; OG_STATE_ACTIVE);
og_group($target_group, $values);
node_save($node);