Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/272.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 带有“while/foreach”的循环;抵销;包装和_Php_Arrays_Loops_Foreach_While Loop - Fatal编程技术网

Php 带有“while/foreach”的循环;抵销;包装和

Php 带有“while/foreach”的循环;抵销;包装和,php,arrays,loops,foreach,while-loop,Php,Arrays,Loops,Foreach,While Loop,在申请了什么之后,我想一切都会结束。但是没有,到目前为止 <?php $faces= array( 1 => '<div class="block">happy</div>', 2 => '<div class="block">sad</div>', (sic) 21 => '<div class="block">angry</div>' ); $i = 1; foreach ($f

在申请了什么之后,我想一切都会结束。但是没有,到目前为止

<?php
$faces= array(
  1 => '<div class="block">happy</div>',
  2 => '<div class="block">sad</div>',
  (sic)
  21 => '<div class="block">angry</div>'
);

$i = 1;
foreach ($faces as $face) {
  echo $face;
  if ($i == 3) echo '<div class="block">This is and ad</div>';
  if ($i % 3 == 0)  {
    echo "<br />"; // or some other wrapping thing
  }
  $i++;
}

?>

您可以将阵列一分为二,插入广告,然后附加其余部分:

// Figure out what your ad looks like:
$yourAd = '<div class="block">This is and ad</div>';

// Get the first two:
$before = array_slice($faces, 0, 2);
// Get everything else:
$after = array_slice($faces, 2);
// Combine them with the ad. Note that we're casting the ad string to an array.
$withAds = array_merge($before, (array)$yourAd, $after);
//看看你的广告是什么样子的:
$yourAd='这是一个广告';
//获取前两个:
$before=数组_切片($faces,0,2);
//获取其他所有信息:
$after=阵列×切片($faces,2);
//请注意,我们正在将广告字符串转换为数组。
$withAds=array\u merge($before,(array)$yourAd,$after);
我认为nickb关于使用比较运算符而不是赋值的说明将有助于了解包装的含义。

首先,插入广告:

array_splice($faces, 2, 0, array('<div class="block">this is an ad</div>'));
array_拼接($faces,2,0,array('这是一个ad'));
然后,应用包装:

foreach (array_chunk($faces, 3) as $chunk) {
    foreach ($chunk as $face) {
        echo $face;
    }
    echo '<br />';
}
foreach(数组\u块($faces,3)作为$chunk){
foreach($chunk作为$face){
回声$脸;
}
回声“
”; }
如果($i=3)
是错误的,如果($i==3)
,则必须是
。您的意思是
数组拼接()
?:)我看过了array_splice的文档,但他们没有清楚地讨论长度为0时会发生什么。很有趣的是,它是这样工作的。@drewish是的,他们只提到了正长度和负长度的行为,尽管在下面的示例片段中提到了:)我想你指的是数组拼接($faces,2…)而不是3。问题是如何让它进入第三个位置,而你的位置将使它进入第四个位置。看起来你也可以放弃添加的包装数组。@drewish谢谢你的评论,我已经应用了位置更改,但我觉得最好还是不使用显式数组。