RonnieT
RonnieT

Reputation: 2203

Combine Two Arrays - First one in order Second one at random

I have the below arrays that I have combined into one. The second array, $ads, is inserted at random into the first array, $EM_Events, but the items inserted always stay together when inserted. I would like for them to be inserted at random throughout the first array, not stay together, and not alter the order of the first array. What am I missing?

$EM_Events = EM_Events::get( array(
'scope'=>'future', 
'limit'=>6,
'category'=>'6'
));

$ads = EM_Events::get( array(
'scope'=>'future', 
'limit'=>2,
'category'=>'56'
));


$offset = array_rand($EM_Events);
array_splice($EM_Events, $offset, 0, $ads);

Upvotes: 2

Views: 269

Answers (2)

user1607653
user1607653

Reputation: 31

What you are trying to do is, 2nd Array is randomised, you try to include it in random places in the 1st array. But after you randomise the 2nd array, make the even spaces of the first array empty ie, the elements in $EM_EVENTS(0),$EM_EVENTS(1), $EM_EVENTS(2),$EM_EVENTS(3) are now saved in $EM_EVENTS(1),$EM_EVENTS(3),$EM_EVENTS(5) etc and the even spaces are filled using a loop. Since the array is already randomised, u get the desired output. clear?

Upvotes: -1

IMSoP
IMSoP

Reputation: 97898

array_splice will only ever perform a single insertion, at some offset in the array, so as you say your second array will stay together.

You will need to loop through all the elements of your second array and insert each in turn. Something like (untested):

foreach ( $ads as $ad ) {
    $offset = array_rand($EM_Events);
    array_splice($EM_Events, $offset, 0, $ad);
}

or perhaps

while ( $ad = array_pop($ads) ) {
    $offset = array_rand($EM_Events);
    array_splice($EM_Events, $offset, 0, $ad);
}

Upvotes: 2

Related Questions