每第六项PHP广告(第一行除外)

时间:2018-09-11 12:56:59

标签: php arrays math

我需要每6个位置添加一个项目。

所以它看起来像这样:

[
   //item1
   //item2
   //item3
   //item4
   //item5
   //NEW ITEM HERE
   //item7
   //item8
   //item9
   //item10
   //item11
   //NEW ITEM
]

我已经尝试过了:

foreach($ports as $key => $port)
{
    if($key %9 == 2) {
        $ports->splice($key, 0, [$ads]);
    }
}

但这没用吗?

5 个答案:

答案 0 :(得分:3)

使用array_chunk并将元素添加到每个子数组:

$portsChunks = array_chunk($ports, 5); // Split array to sub-arrays of max-5 elements.

// Add new element if chunk is full length.
// Means last one will not receive new element if it's shorter than 5
array_walk($portsChunks, function (&$array) {
    if (count($array) == 5) {
        $array[] = 'New Item';
    }
});

// Use arguments unpacking to pass all chunks to array_merge
$ports = array_merge(...$portsChunk);

Example

答案 1 :(得分:1)

您可以使用foreach循环:

$ports = range(1,50);
$new_ports = [];
foreach ($ports as $key => $port) {
    $new_ports[] = $port;
    if(!(($key+1)%5))
        $new_ports[] = 'New item';
}
print_r($new_ports);

答案 2 :(得分:0)

我希望以下情况能解决您的问题:

$newarr = array();

    $cnt = 1;


    foreach($arr as $key=>$value){

            $newarr[] = $value;

            if($cnt%5 == 0){

            $newarr[] = 'this is new item';

        }

            $cnt++;

    }
print_r($newarr);

答案 3 :(得分:0)

    $ports = [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6];
    $ports = array_chunk($ports, 5);
    foreach ($ports as &$port){
        array_push($port, 'new value');
    }
    unset($port);
    if(count($ports[count($ports)-1]) < 6){
        array_pop($ports[count($ports)-1]);
    }
    $ports = array_merge(...$ports);

答案 4 :(得分:0)

您只需要一个新数组即可保存所有数据。然后遍历旧数组,并在第5个位置之后插入一个新元素。像这样

x
相关问题