如何遍历多维数组以从每种颜色中获取随机图像?

时间:2016-03-07 20:03:52

标签: php arrays multidimensional-array

我希望遍历下面的数组,然后用每个颜色数组中的1个随机图像填充<UL>。我无法理解如何访问特定的颜色数组......我需要一个循环吗?或者array_rand()是否足够?我该怎么做呢?

$colors = array( 
    'green' => array(
        'images/green1.jpg',
        'images/green2.jpg',
        'images/green3.jpg',
        'images/green4.jpg',
        'images/green5.jpg'
        ),
    'red' => array(
        '/images/red1.jpg',
        '/images/red2.jpg',
        '/images/red3.jpg',
        '/images/red4.jpg',
        '/images/red5.jpg'
        ),
    'blue' => array(
        '/images/blue1.jpg',
        '/images/blue2.jpg',
        '/images/blue3.jpg',
        '/images/blue4.jpg',
        '/images/blue5.jpg'
        ),
    'purple' => array(
        '/images/purple1.jpg',
        '/images/purple2.jpg',
        '/images/purple3.jpg',
        '/images/purple4.jpg',
        '/images/purple5.jpg'
        )
    );

<div>
    <span>Colors</span>
        <ul>
            <li>"1 img from 'green' array would go here"</li>
            <li>"1 img from 'red' array would go here"</li>
            <li>"1 img from 'blue' array would go here"</li>
            <li>"1 img from 'purple' array would go here"</li>
        </ul>
</div>

4 个答案:

答案 0 :(得分:2)

正如您所提到的,可以使用array_rand(),但您需要遍历颜色。对于每一个,获得一个随机图像:

$arr = array();
foreach($colors as $k=>$v){
    $arr[] = $v[array_rand($v)];
}

print_r($arr);

输出1:

Array
(
    [0] => images/green3.jpg
    [1] => /images/red3.jpg
    [2] => /images/blue2.jpg
    [3] => /images/purple1.jpg
)

再次跑步:

Array
(
    [0] => images/green5.jpg
    [1] => /images/red3.jpg
    [2] => /images/blue1.jpg
    [3] => /images/purple4.jpg
)

如果你想像问题一样输出它,它将是这样的:

// div span ul
$arr = array();
foreach($colors as $k=>$v){
    echo '<li><img src="' . $v[array_rand($v)] . '"></li>';
}
// /div /ul

旁注:

答案 1 :(得分:0)

foreach ($colors as $color){
    $image = array_rand($color);
    echo '<li>' . $color[$image] . '</li>';
}

答案 2 :(得分:0)

我会像

那样
foreach ($colors as $color){
     //This gets you each color array in turn, in here you can 
     //use array_rand() to get a random entry from each array.

}

答案 3 :(得分:0)

这对我有用:

<?php
$colors = array(
'green' => array(
'images/green1.jpg',
'images/green2.jpg',
'images/green3.jpg',
'images/green4.jpg',
'images/green5.jpg'
),
'red' => array(
'/images/red1.jpg',
'/images/red2.jpg',
'/images/red3.jpg',
'/images/red4.jpg',
'/images/red5.jpg'
),
'blue' => array(
'/images/blue1.jpg',
'/images/blue2.jpg',
'/images/blue3.jpg',
'/images/blue4.jpg',
'/images/blue5.jpg'
),
'purple' => array(
'/images/purple1.jpg',
'/images/purple2.jpg',
'/images/purple3.jpg',
'/images/purple4.jpg',
'/images/purple5.jpg'
)
);
?>
<div>
    <span>Colors</span>
    <ul>
        <?php
        foreach ($colors as $key=>$value){
            echo '<li>'.$value[array_rand($value,1)]."</li>";
        }
?>
    </ul>
</div>