2011-12-07 153 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#,所以我不知道它是如何处理它们的。 –