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


How do I loop through a multidimensional array to get a random image from each color?

我希望遍历下面的数组,然后用每个颜色数组中的 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>

正如你提到的,可以使用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

旁注:

  • 数组中的 green url 缺少前导/(或者其他所有颜色都有一个备用,我不知道);
  • 此代码检查图像是否存在(file_exists/PHP:如何检查图像文件是否存在?

我会这样

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.
}

这对我有用:

<?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>
foreach ($colors as $color){
    $image = array_rand($color);
    echo '<li>' . $color[$image] . '</li>';
}