在第一个内部随机注入第二个数组

时间:2015-04-10 20:53:24

标签: php arrays

我有两个数组,一个用于显示图像,另一个用于广告:

$ads = Array
(
    [0] => stdClass Object
        (
            [description] => Long Ad
        )

    [1] => stdClass Object
        (
            [description] => Tower Ad
        )

    [2] => stdClass Object
        (
            [description] => Small Ad
        )

)

$images = Array
(
    [0] => stdClass Object
        (
            [title] => My House
        )

    [1] => stdClass Object
        (
            [title] => Forest Panorama
        )

    [2] => stdClass Object
        (
            [title] => Dog Picture
        )

    [3] => stdClass Object
        (
            [title] => Sunset
        )

    [4] => stdClass Object
        (
            [title] => Sunrise
        )

)

我尝试使用以下代码:

foreach ($images as $i=> $row) {
    $offset = array_rand($images);
    array_splice($images, $offset, 0, $ads);
    print $row->description . "<br>";

}

在上面我只得到三条记录,而不是总共八条。我想随机在循环中插入$ ads数组。 $ images数组的顺序必须保持不变,而$ ads数组则在随机位置注入。

1 个答案:

答案 0 :(得分:1)

所以最后,我认为这是你想要的,它应该适合你:

<?php

    $tmp = $ads;

    foreach($images as $v) {
        if(rand(1, 100) >= 40) { //To 60%(100-40) percent an ads element gets injected 
            $key = array_rand($tmp, 1);
            $v->description = $ads[$key]->description;
            unset($tmp[$key]);
        }
    }

?>

要显示数据使用:

foreach($images as $image) {
    echo "image: " . $image->title . (isset($image->description)?(" | description: " . $image->description . "<br>"):"<br>");
}

示例输出:

image: Dog picture | description: Small Ad
image: Sunset
image: Sunrise | description: Long Ad