我的代码中有一个数组($keys
),我只想显示前10个元素。我尝试了一个foreach循环,但它只显示了所有元素。
而不是:
"72.4x.xxx.xxx","90.18x.xxx.xxx","177.9x.xxx.xxx",
我希望像这样查看它们:
xxx.xxx.xxx
yyy.yyy.yyy
//etc.
for ($i = 0; $i < count($keys); $i++); {
return $keys;
}
答案 0 :(得分:0)
如果数组如下所示:
implode()
将array_chunk()
和<br />
与$topTen = array_chunk($array,10);
echo implode("<br />".PHP_EOL,$topTen[0]);
72.4x.xxx.xxx
90.18x.xxx.xxx
177.9x.xxx.xxx
72.4x.xxx.xxx
90.18x.xxx.xxx
177.9x.xxx.xxx
72.4x.xxx.xxx
90.18x.xxx.xxx
177.9x.xxx.xxx
72.4x.xxx.xxx
给你(显示):
72.4x.xxx.xxx<br />
90.18x.xxx.xxx<br />
177.9x.xxx.xxx<br />
72.4x.xxx.xxx<br />
90.18x.xxx.xxx<br />
177.9x.xxx.xxx<br />
72.4x.xxx.xxx<br />
90.18x.xxx.xxx<br />
177.9x.xxx.xxx<br />
72.4x.xxx.xxx
给你(来源):
echo -n "ŻÓŹŁŃĘ"|wc -m
6
echo -n "ŻÓŹŁŃĘ"|wc -c
12
答案 1 :(得分:0)
删除for循环后面的;
。如果你在循环中return
,它将只运行一次并返回数组$keys
如果你想在循环中出于某种原因,可能在x元素之后休息或者你可以尝试下面的代码。
您可以使用break:if( $i == 10 ) break;//$i is you index count
$keys = array(
"72.4x.xxx.xxx",
"90.18x.xxx.xxx",
"177.9x.xxx.xxx",
);
$output = "";
for ($i = 0; ( $i < count($keys) ); $i++)
{
// how many elements you want to show? i.e. 10
if( $i == 10 ) break;
$output .= $keys[$i]."<br>";// line break \n or html <br>
}
echo $output;
// i would prefer the foreach
$output = "";
// add index
foreach( $keys as $index => $key )
{
// how many elements you want to show? i.e. 10
if( $index == 10 ) break;
$output .= $key."<br>";// line break \n or html <br>
}
echo $output;