将数组中的字符串替换为截断字符串
我在我的网站上使用 CodeIgniter。我还在我的网站上使用 tumblr API 来显示发布的新闻。
因为显示整个文本有点太多,所以我想将正文截断为 150 个字符,我通过使用 CI 的 character_limiter
函数来完成此操作。
我的“home”控制器中的代码如下:
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 中不起作用,任何人都知道为什么以及如何解决它,或者还有其他方法吗?
I'm using CodeIgniter for my website. I'm also using the tumblr API on my site to show posted news.
Because showing the entire text is a bit too much, I want to truncate the body copy to 150 characters, I do this by using the character_limiter
function of CI.
The code is as followed in my 'home' controller:
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);
}
The problem is, that $tumblr_post['body']
isn't shortened when I echo it on my view page. Doing it like above works in Asp.net (C#) but it doesn't seem to work in php, anyone know why and how to solve it or is there an other way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题出在
foreach
循环上。您需要在$tumblr_post
之前添加&
以通过引用传递它。这可确保您实际上正在编辑数组中的值。如果没有&
,您只是编辑局部变量而不是数组。像这样尝试(注意
&
):Your problem is with the
foreach
loop. You need to add a&
before$tumblr_post
to pass it by reference. This makes sure you are actually editing the values in the array. Without the&
, you're just editing a local variable and not the array.Try it like this (notice the
&
):