0

I have two array:

$divs = array('One','Two','Three','Four','Five','Six');
$ads = array ('Ad1', 'Ad2', 'Ad3');

I want merge like this:

$mix_divs = array_merge($divs, $reklama);

But, $divs must stay in same places and between this places I need to add random $ads array.

shuffle($ads);

Final input must be something like this:

$mix_divs = array('One','Two','Ad2','Three','Four','Ad3','Five','Six','Ad1');

or

 $mix_divs = array('Ad2','One','Two','Ad1','Three','Four','Five','Ad3','Six');

$ads must be random inserted.

How can I do that? Thanks

2
  • if you want the elements to stay in place, you're not looking for array_merge, you want to use array_splice to inject the $ads array elements. Commented Mar 2, 2015 at 21:38
  • You have not completely defined your question: Are there always six divs and three ads? Do you always want two divs between two ads? Commented Mar 2, 2015 at 21:53

2 Answers 2

1

You just insert each ad in a random position in divs:

$divs = array('One','Two','Three','Four','Five','Six');
$ads = array ('Ad1', 'Ad2', 'Ad3');

$newArray = array_merge($divs);
for ($i = 0; $i < count($ads); $i++) {
    $position = rand(0, count($newArray));
    array_splice($newArray, $position, 0, $ads[$i]);
}

I just tried to print_r($newArray) and it gave me:

Array
(
    [0] => One
    [1] => Two
    [2] => Three
    [3] => Ad2
    [4] => Four
    [5] => Ad1
    [6] => Five
    [7] => Ad3
    [8] => Six
)
Sign up to request clarification or add additional context in comments.

Comments

1
$divs = array('One','Two','Three','Four','Five','Six');
$ads  = array('Ad1', 'Ad2', 'Ad3');

shuffle($ads);
while ($ads) array_splice($divs, array_rand($divs), 0, array_pop($ads));

print_r($divs);

Output:

Array
(
    [0] => Ad1
    [1] => One
    [2] => Two
    [3] => Ad3
    [4] => Three
    [5] => Four
    [6] => Five
    [7] => Ad2
    [8] => Six
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.