将1个元素从一个数组推送到另一个数组

时间:2017-11-06 09:16:19

标签: php arrays loops sorting

我知道这是可能的但不确定我的情况。所以目前我有2个阵列。一个用于广告,另一个用于事件。我想为每3个活动添加一个广告。简单解释他们目前的情况。

事件数组:

$Events =Array('Event 1','Event 2','Event 3','Event 4','Event 5','Event 6','Event 7') ;

广告阵列:

$Adverts =Array('Advert 1','Advert 2');

目标阵列:

$Target = Array('Event 1','Event 2','Event 3','Advert 1','Event 4','Event 5','Event 6','Advert 2');

我目前将事件数组块化,使它们成为3组。

3 个答案:

答案 0 :(得分:1)

您正在寻找array_splice

这应该有用。

 $event_array = ['Event 1','Event 2','Event 3','Event 4','Event 5','Event 6','Event 7'];
$advert_array = ['Advert 1','Advert 2'];
//Push array value;
array_splice($event_array, 3, 0,array($advert_array[0]));
//Add to index 3
array_splice($event_array, 3, 0,$advert_array[0]);
print_r($event_array);

<强>结果

Array ( [0] => Event 1 [1] => Event 2 [2] => Event 3 [3] => Advert 1 [4] => Event 4 [5] => Event 5 [6] => Event 6 [7] => Advert 2 )

答案 1 :(得分:1)

你可以试试这个:

$Events =array('Event 1','Event 2','Event 3','Event 4','Event 5','Event 6','Event 7') ;
$Adverts =array('Advert 1','Advert 2');
$Target =array();

$AdvertCount = 0;
foreach ($Events as $key => $Event) {
    array_push($Target,$Event);
    if (($key + 1) % 3 == 0) {
        array_push($Target,$Adverts[$AdvertCount]);
        $AdvertCount++;
    }
}

print_r($Target);

答案 2 :(得分:0)

最简单的方法之一是迭代$Adverts$Adverts的每个项目从$Events中提取三个项目:

$Events = array('Event 1','Event 2','Event 3','Event 4','Event 5','Event 6','Event 7');
$Adverts = array('Advert 1','Advert 2');

$Target = array();
// The current position in $Events
$i = 0;
foreach ($Adverts as $advert) {
    // Append 3 events and the current advert
    $Target = array_merge($Target, array_slice($Events, $i, 3), array($advert));
    // Skip over the 3 events just processed
    $i += 3;
}

为了确保您没有用完事件,您应首先计算迭代次数。以下代码仅在$Target中放入3个事件+ 1个广告的完整组。

// The number of events in each group
$nbEvents = 3;
// The number of groups; each group contains $nbEvents events + 1 advert
$nbGroups = min((int)(count($Events)/$nbEvents), count($Adverts));

$Target = array();
// Iterate over $Adverts but process only $nbGroups items
for ($i = 0; $i < $nbGroups; $i ++) {
    // Append $nbEvents events and the current advert
    $Target = array_merge(
        $Target,
        array_slice($Events, $nbEvents * $i, $nbEvents),
        array($Adverts[$i])
    );
}