PHP foreach()循环

时间:2016-02-18 14:12:55

标签: php

$string = "The complete archive of The New York Times can now be searched from NYTimes.com " //the actual input is unknown, it would be read from textarea  

$size = the longest word length from the string 

我在for循环中分配并初始化了数组,例如array1,array2 .... arrayN,这是我的做法

for ($i = 1; $i <= $size; $i++) {
    ${"array" . $i} = array();
}

所以$ string将被分成单词的长度

$array1 = [""];
$array2 = ["of", "be", ...]
$array3 = ["the", "can", "now", ...] and so on 

所以,我的问题是如何将简单的for循环或foreach循环$ string值分配给$ array1,$ array2,$ array3 .....,因为输入文本或最长单词的大小未知< / p>

4 个答案:

答案 0 :(得分:3)

我可能会从$words = explode(' ', $string)开始 然后按字长

对字符串进行排序
usort($words, function($word1, $word2) {
    if (strlen($word1) == strlen($word2)) {
        return 0;
    }
    return (strlen($word1) < strlen($word2)) ? -1 : 1;
});

$longestWordSize = strlen(last($words));

循环显示单词并放置在各自的存储桶中。 你应该考虑像

这样的东西,而不是为每个长度数组分开变量
$sortedWords = array(
    1 => array('a', 'I'),
    2 => array('to', 'be', 'or', 'is'),
    3 => array('not', 'the'),
);

通过循环显示您不需要知道最大字长的单词。

最终的解决方案就像

一样简单
foreach ($words as $word) {
    $wordLength = strlen($word);
    $sortedWords[ $wordLength ][] = $word;
}

答案 1 :(得分:0)

您可以使用以下内容:

$words = explode(" ", $string);
foreach ($words as $w) {
    array_push(${"array" . strlen($w)}, $w);
}

$string拆分为$words数组,然后计算每个单词的长度,并将该单词推送到相应的数组。

答案 2 :(得分:0)

you can use explode().

$string = "The complete archive of The New York Times can now be searched           from NYTimes.com " ;

$arr=explode(" ",$string);
$count=count($arr);

$big=0;
 for ($i = 0; $i < $count; $i++) {
     $p=strlen($arr[$i]);
if($big<$p){ $big_val=$arr[$i]; $big=$p;}

     }
echo $big_val;

答案 3 :(得分:0)

只需使用单词长度作为索引,并在每个单词后附加[]

foreach(explode(' ', $string) as $word) {
    $array[strlen($word)][] = $word;
}

删除重复项$array = array_map('array_unique', $array);

收率:

Array
(
    [3] => Array
        (
            [0] => The
            [2] => New
            [3] => can
            [4] => now
        )

    [8] => Array
        (
            [0] => complete
            [1] => searched
        )

    [7] => Array
        (
            [0] => archive
        )

    [2] => Array
        (
            [0] => of
            [1] => be
        )

    [4] => Array
        (
            [0] => York
        )

    [5] => Array
        (
            [0] => Times
        )
)

如果要使用array_values()重新索引主数组并重新索引子数组,请将array_map()array_values()一起使用。