2011-12-07 151 views
2

我正在爲我的網站使用CodeIgniter。我還在我的網站上使用tumblr API來顯示發佈的新聞。使用截斷字符串替換數組中的字符串

由於顯示整個文本有點太多,我想截斷正文副本爲150個字符,我通過使用CI的character_limiter函數來完成此操作。

的代碼是跟隨我的「家」控制器:

public function index() {  
    //Title for home page 
    $data['title'] = "Home - Welcome"; 

    // Obtain an array of posts from the specified blog 
    // See the config file for a list of settings available 
    $tumblr_posts = $this->tumblr->read_posts(); 

    foreach($tumblr_posts as $tumblr_post) { 
     $tumblr_post['body'] = character_limiter($tumblr_post['body'], 150); 
    } 

    // Output the posts 
    $data['tumblr_posts'] = $tumblr_posts;  

    // Load the template from the views directory 
    $this->layout->view('home', $data); 
} 

的問題是,當我贊同它在我的視圖頁面上$tumblr_post['body']不會縮短。像上面這樣做在Asp.net(C#)中工作,但它似乎無法在PHP中工作,任何人都知道爲什麼以及如何解決它或有其他方法嗎?

+0

是否包含文字幫手..? –

+0

我鼓勵你在視圖中做這個,而不是控制器。 –

+0

請發佈函數character_limiter()的代碼? – elias

回答

1

您的問題是與foreach循環。您需要在$tumblr_post之前添加&以通過引用傳遞它。這確保您實際上正在編輯數組中的值。沒有&,你只是編輯一個局部變量而不是數組。

嘗試像這樣(注意&):

foreach($tumblr_posts as &$tumblr_post) { 
    $tumblr_post['body'] = character_limiter($tumblr_post['body'], 150); 
} 
+0

是的,就是這樣:)謝謝。 是(OO)C#中的&&類似的東西嗎? –

+0

@reaper_unique:'&'告訴PHP通過引用傳遞變量。我不知道C#,所以我不知道它是如何處理它們的。 –