php基本操作问题

时间:2011-07-02 21:45:48

标签: php

我有50个元素的数组。这个数组可以是任何大小。 我希望在字符串中包含数组的前10个元素。

我的节目如下:

$array1= array("itself", "aith","Inside","Engineer","cooool","that","it","because");

$i=0;
for($f=0; $f < sizeof(array1); $f++)
{
    $temparry = $temparry.array1[$f];

    if(($f%10) == 0 && ($f !== 0))
    {
         $temparray[$i] = $temparray;
         $i++;   
    }
}

== 所以最后:
我得到了 temparray1 =前10个元素
temparray2 - 接下来的10个元素......

我不是我在循环中失踪的东西。

4 个答案:

答案 0 :(得分:1)

您可以使用array_spliceimplode轻松完成此操作。

示例:

<?php

$array = range(1, 50);

while ( $extracted = array_splice($array, 0, 10) )
{
  // You could also assign this to a variable instead of outputting it.
  echo implode(' ', $extracted); 
}

答案 1 :(得分:1)

阅读完评论后,我认为您需要array_chunk [docs]

$chunks = array_chunk($array1, 10);

这将创建一个多维数组,每个元素都是一个包含10个元素的数组。

如果您仍想将其加入字符串,可以使用array_map [docs]implode [docs]

$strings = array_map('implode', $chunks);

这为您提供了一个字符串数组,其中每个元素都是一个块的串联。

答案 2 :(得分:0)

您在这里所做的就是创建一个临时值,然后将其删除。将其保存为字符串:

$myArray = array("itself", "aith","Inside","Engineer",
                 "cooool","that","it","because");
$myString = '';

for($i = 0; $i < 10; $i++) {
    $myString .= $myArray[$i];
}

您也可以在另一个for循环中运行,该循环将贯穿整个数组,为您提供十个元素的增量。

答案 3 :(得分:0)

实际上你可以使用arrray_slice和implode这样的函数:

// put first 10 elements into array output
$output = array_slice($myArray, 10);

// implode the 10 elements into a string
$str = implode("", $output);

OP的固定代码,如下所示:

$array1= array("itself","aith","Inside","Engineer","cooool","that","it","because");
$temparry='';
$temparray = array();
for($f=0; $f < count($array1); $f++)
{
    $temparry = $temparry.$array1[$f];
    if(($f%3) == 0 && ($f !== 0))
    {
         $temparray[] = $temparry;
         $temparry = '';
    }
}
print_r($temparray);