2011-04-18 57 views
0

試圖在函數中返回一個數組。沒有好運...返回PHP中數組的問題

(flag_friend_get_friends()方法返回包含數組的對象列表的功能)

因此,沒有一個功能,這個工程:

<?php 

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

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

    $test = $users_friends_ids; 

    print $test[0]; 

    ?> 

如果我嘗試和包裝它的功能,它不起作用(沒有打印)...:

  <?php 

     function myfunc() {   

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

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

     return $users_friends; 

     } 


     $test = myfunc(); 

     print $test[0]; 

     ?> 

什麼是'故意的'錯誤? :(

更新代碼:

<?php 
function myfunc() {   

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

return $users_friends; 
} 

$test = myfunc($user); 
print $test[0]; 
?> 

回答

3

你需要傳遞$user到您的功能,當你把它叫做:

$測試= myfunc($user)

UPDATE:

<?php 
function myfunc ($user) {   

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

return $users_friends; 
} 

$test = myfunc($user); 
print $test[0]; 
?> 

這是w你的代碼需要看起來像。

+0

恐怕這似乎不起作用。這變成了一場噩夢... – james6848 2011-04-18 15:17:54

+0

你能發佈更新後的代碼嗎? – 2011-04-18 15:58:01

+0

我會在上面貼出來,歡呼聲。 – james6848 2011-04-18 16:15:21

2

而且您需要傳遞$ users_friends_ids的引用或在函數中將其聲明爲全局。

問題是,當你將東西移動到一個函數中時,它無法再訪問你的局部變量。

+0

$ users_friends_ids []應該可以工作,即使在函數內沒有正確聲明。在這種情況下,PHP只是將$ users_friends_ids創建爲一個數組並向其添加元素。 – 2011-04-18 13:58:00

+0

它不會「工作」,因爲它不在函數外部可用。在上面的代碼中,他沒有在函數之外訪問它,但是我的觀點是,當你將代碼移動到一個函數中時,一個常見的問題就是你無法再訪問同一個變量範圍。 – 2011-04-18 15:10:43

2

在drupal中,$ user是全局的。所以,如果這個函數總是要拉入當前用戶的朋友,你只需要在函數的頂部定義它。

function myfunc() {   
    // pull in the global $user var 
    global $user; 

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

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

    return $users_friends; 
}