Drupal - 如何使数组全局可访问?

jam*_*848 6 php drupal drupal-views drupal-6

我在视图字段模板中使用此代码(在本例中为views-view-field - all-members - uid.tpl.php):

<?php

$users_friends = flag_friend_get_friends($user->uid);

$users_friends_ids = array();

foreach ($users_friends as $id => $value) {     
 $users_friends_ids[] = $id;    
}


?>
Run Code Online (Sandbox Code Playgroud)

它基本上获取朋友的用户ID并将它们放在一个数组中,以便我可以检查该字段是否与任何用户ID匹配.

所以我的问题是我不想在这个模板中有这个(出于几个原因),但如果我不这样做,我就无法访问该数组.如何使这个数组全局可访问?

Cod*_*er1 5

如果不知道你的"几个原因",我不能说这是否是肯定的答案.我自己的原因可能是我不希望相同的代码执行很多次,而我宁愿在多个地方没有相同的确切代码.

然后我会创建一个带有静态变量的函数来保存friends数组.

function mymodule_get_friends_ids() {
  // pull in the current global user variable
  global $user;

  // call up the static variable
  static $users_friends_ids;
  // return if this static var has already been set
  if (is_array($users_friends_ids)) {
    return $users_friends_ids;
  }

  // if we hit here, then this function has not been
  // run yet for this page load.

  // init array
  $users_friends_ids = array();

  // if user is anon, no need to go on
  if (user_is_anonymous()) {
    return $users_friends_ids;
  }

  // get friends array
  $users_friends = flag_friend_get_friends($user->uid);

  // build ids array
  foreach ($users_friends as $id => $value) {     
    $users_friends_ids[] = $id;    
  }

  return $users_friends_ids;
}
Run Code Online (Sandbox Code Playgroud)

现在在模板中,您可以在任意多个位置调用mymodule_get_friends_ids(),第一次返回下面的工作代码只会在第一次调用时执行.