【问题标题】:php array combine values until string limit reachedphp数组组合值直到达到字符串限制
【发布时间】:2015-10-10 17:38:12
【问题描述】:

我有一个包含一定长度字符的字符串数组:

数组
(
    [0] => 

foo

[1] =>

条形

[2] =>

你好

[3] =>

世界

[4] =>

[5] =>

太棒了

)

我需要将这些值组合成块,直到达到某个字符串长度限制。

例如最大字符数为 6

所以新数组看起来像这样

数组
(
    [0] => 富吧
    [1] => 你好
    [2] => 世界
    [3] => 很棒
)

"Foo" 和 "Bar"、"i" 和 "world" 合并,因为它不超过 6 max allowed char 限制。 但是“你好”不要因为组合字符限制超过 6。

不知道该怎么做。

【问题讨论】:

    标签: php arrays


    【解决方案1】:

    简单:

    $arr = array('foo','bar','hello', 'world', 'i', 'great');
    $limit = 6;
    $result = array(''); // some hack
    $cur_key = 0;        // some hack
    foreach ($arr as $word) {
        if (strlen($result[$cur_key]) + strlen($word) <= $limit) {
            $result[$cur_key] .= $word;
        } else {
            $result[] = $word;
            $cur_key++;
        }
    }
    

    【讨论】:

    • 数组函数的存在是有原因的。
    • 什么数组函数?什么原因?
    • 您正在使用 foreach、strlen 和 if 手动执行此操作。 implode 和 str_split 是你的朋友。
    • 你的函数甚至没有做 OP 想要的。
    • 这不是“我的”功能。这是php的。你应该再试一次。
    【解决方案2】:

    非常简单:

    // YOUR ARRAY
    $array = array('foo', 'bar', 'hello', 'world', 'i', 'great');
    
    // STRING CONTAINING YOUR ARRAY VALUES CONCATENATED
    $alltogheter = implode("", $array);
    
    // NEW ARRAY FROM YOUR STRING (SPLIT BY 6 CHARS)
    $newarray = str_split($alltogheter, 6);
    

    【讨论】:

    • 函数结果:array(4) { [0]=&gt; string(6) "foobar" [1]=&gt; string(6) "hellow" [2]=&gt; string(6) "orldig" [3]=&gt; string(4) "reat" }
    • 完全正确。我在 OP 的数组中看不到任何空格。
    • OP想要[1] =&gt; hello [2] =&gt; worldi你给他:[1]=&gt; string(6) "hellow" [2]=&gt; string(6) "orldig"
    • 你知道你的代码返回的结果不是 OP 想要的吗?
    • 是的,我可以读到:我需要将这些值组合成块,直到达到某个字符串长度限制。例如最大字符数为 6
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-15
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 2011-11-21
    • 1970-01-01
    • 2023-01-22
    相关资源
    最近更新 更多