简体   繁体   English

在 PHP 中使用交替颜色打印阵列

[英]Print array with alternate colour in PHP

I have an array,我有一个数组,

$arr = arrary("Pune","Nashik","Mumbai");

I want to display Pune in red colour, then on the next line Nashik will be blue and the last line will have Mumbai in green.我想以红色显示Pune ,然后在下一行Nashik将显示为蓝色,最后一行将Mumbai显示为绿色。 How do I do this using a " while loop ".我如何使用“ while 循环”来做到这一点。

Like,喜欢,

Pune (in red) 
Nashik (in blue) 
Mumbai (in green)

Why don't you simply build the logic into the array, eg为什么不简单地将逻辑构建到数组中,例如

$arr = array(
    'Pune'   => '#ff0000',
    'Nashik' => '#0000ff',
    'Mumbai' => '#00ff00'
);

Then, when you loop over it, use CSS to display the colours.然后,当你循环它时,使用 CSS 来显示颜色。

<?php foreach ($arr as $something => $colour) : ?>
    <p style="color:<?php echo $colour ?>"><?php echo $something ?></p>
<?php endforeach ?>

You could also use CSS class names instead of hex colour values.您还可以使用 CSS class 名称而不是十六进制颜色值。

Also, a while loop is hardly the best option for iterating over an array.此外, while循环并不是遍历数组的最佳选择。

Edit: Oops, accidentally deleted my second example.编辑:糟糕,不小心删除了我的第二个示例。 It's back now现在又回来了

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM