php - 获取数组中每个元素的字符串长度

时间:2015-01-21 22:25:23

标签: php

我正在尝试设置网站上每个帖子的最大长度,但strlen()不适用于数组。所以我需要将其分解以检查数组中的每个帖子。

如果法规工作正常,我怎么能适应我的要求呢?问题是strlen()不接受对象。

    for($i = 0, $size = count($somePosts); $i < $size; ++$i) {
        if (strlen(utf8_decode($somePosts[$i])) > $max_length) {
            $offset = ($max_length - 3) - strlen($somePosts);
            $somePosts = substr($somePosts, 0, strrpos($reviewPosts, ' ', $offset)) . '...';
        }
    }

我正在使用Doctrine生成数组,工作正常。

感谢。

编辑:

错误 - 警告:strlen()期望参数1为字符串,给定对象

编辑2:

现在没有错误消息,但代码在限制帖子长度方面不起作用。

2 个答案:

答案 0 :(得分:3)

您需要访问当前数组项,例如$somePosts[$i]而不是$somePosts

for($i = 0, $size = count($somePosts); $i < $size; ++$i) {
    if (strlen(utf8_decode($somePosts[$i])) > $max_length) {
        $offset = ($max_length - 3) - strlen($somePosts[$i]);
        $somePosts[$i] = substr($somePosts[$i], 0, strrpos($reviewPosts, ' ', $offset)) . '...';
    }
}

答案 1 :(得分:0)

作为替代方案,您可以使用array_map

<?php

$strs = array('abcdefgh', 'defghjklmn', 'ghjefggezgzgezg');
$max = 5;
$strs = array_map(function($val) use ($max) {
    if (strlen($val.'') < $max) return $val.'';
    return substr($val.'', 0,$max-3).'...';
},$strs);

var_dump($strs);

EDIT隐式强制转换添加到强制转换对象

相关问题