2016-06-07 90 views
0

我正在使用此代碼來獲取已張貼在當前類別中的所有作者的名字:設定功能結果作爲變量

function categoryAuthors() { 
    $category_authors = array(); 
    $args = array(
     'posts_per_page'  => -1, 
     'category'   => $category, 
     'post_status'  => 'publish' 
    ); 
    $allposts = get_posts($args); 
    if ($allposts) { 
     foreach($allposts as $authorpost) { 
      $category_authors[$authorpost->post_author]+=1; 
     } 
     arsort($category_authors); 
     foreach($category_authors as $key => $author_post_count) { 
      $user = get_userdata($key); 
      $an_author = "'" . $user->first_name . "', "; 
      echo $an_author; 
     } 
    } 
} 


$theAuthors = categoryAuthors(); 
echo $theAuthors; 

..這幾乎是工作,但是,如果我註釋掉回聲像這樣...

// echo $theAuthors; 

...所有的電子郵件地址都在我的網頁上回應,無論。

我的理解是,一個函數不會被調用,直到你真的調用它,但它似乎被稱爲(輸出在頁面上),即使我不echo $ theAuthors。

無論如何,我想做一個變量,這是一個逗號分隔的作者名字列表,以便我可以在其他地方使用它。

我該如何解決這個問題?

乾杯。

+3

你的函數需要_return_東西! – jszobody

+0

什麼?您在使用'()'運算符時調用該函數。此外,你正在迴應函數體中的'$ an_author'變量。 –

+0

你知道'echo'與'print'是一樣的嗎? –

回答

3

使用()返回到功能

function categoryAuthors() { 
    $an_author = ''; 
    $category_authors = array(); 
    $args = array(
     'posts_per_page'  => -1, 
     'category'   => $category, 
     'post_status'  => 'publish' 
    ); 
    $allposts = get_posts($args); 
    if ($allposts) { 
     foreach($allposts as $authorpost) { 
      $category_authors[$authorpost->post_author]+=1; 
     } 
     arsort($category_authors); 
     foreach($category_authors as $key => $author_post_count) { 
      $user = get_userdata($key); 
      $an_author .= "'" . $user->first_name . "', "; 
     } 
    } 
    return $an_author; 
} 


$theAuthors = categoryAuthors(); 
echo $theAuthors; 
+2

還應該注意他正在使用字符串連接(這是'。='是),所以你得到一個完整的字符串 – Machavity

+0

'$ category'來自'$ args'數組?這個功能仍然不起作用。 – jszobody

+0

@jszobody這並不完全公平,OP已經明確表示該函數在回顯數據時工作,所以這個答案的變化將使其工作... – jeroen

0

您的函數沒有返回語句這就是爲什麼當你調用函數返回不變量。然而你有一個echo語句,這意味着當你調用這個函數時,它只會打印所有的名字。

要解決此問題,請刪除每個循環迭代中每行回聲字符串的行,而是使用所有名稱構建一個字符串,然後在函數結束時將其返回。

例子:

<?php 
function categoryAuthors() { 
    $category_authors = array(); 
    $names = ''; 
    $args = array(
     'posts_per_page'  => -1, 
     'category'   => $category, 
     'post_status'  => 'publish' 
    ); 
    $allposts = get_posts($args); 
    if ($allposts) { 
     foreach($allposts as $authorpost) { 
      $category_authors[$authorpost->post_author]+=1; 
     } 
     arsort($category_authors); 
     foreach($category_authors as $key => $author_post_count) { 
      $user = get_userdata($key); 
      $an_author = "'" . $user->first_name . "', "; 
      //echo $an_author; 
      $names = "$names, $an_author"; 
     } 
    } 
    return $names; 
} 


$theAuthors = categoryAuthors(); 
echo $theAuthors; 
?> 
+0

現在看看;) –