【问题标题】:Change color block based on string % with array使用数组根据字符串 % 更改颜色块
【发布时间】:2018-06-25 23:34:32
【问题描述】:

我有值:1,5,7,2,25,2,6,我想为所有值指定一个与颜色相关的特定百分比。

所以最高值为25 -100%。 最低值为1 - 10%。

这是具有许多值的预览外观:

有了这些数字,我想检查其他数字 %,但我想用其他 10 种颜色做同样的事情:

.100 {
  color: rgb(30, 144, 255);
}
.90 {
  color: rgba(30, 144, 255, 0.9);
}
.80 {
  color: rgba(30, 144, 255, 0.8);
}
.70 {
  color: rgba(30, 144, 255, 0.7);
}
.60 {
  color: rgba(30, 144, 255, 0.6);
}
.50 {
  color: rgba(30, 144, 255, 0.5);
}
.40 {
  color: rgba(30, 144, 255, 0.4);
}
.30 {
  color: rgba(30, 144, 255, 0.3);
}
.20 {
  color: rgba(30, 144, 255, 0.2);
}
.10 {
  color: rgba(30, 144, 255, 0.1);
}

到目前为止我尝试过:

$a_c_a = '1,5,7,2,25,2,6';

$a_c_a_min = min(array_filter($a_c_s));
$a_c_a_max = max(array_filter($a_c_s));

$a_c_a_min_10 = $a_c_a_min;
$a_c_a_max_100 = $a_c_a_max;

if (1 == $a_c_a_max) {
  $class_2 = '.100';
} elseif (1 == $a_c_a_min) {
  $class_2 = '.10';
}

if (5 == $a_c_a_max) {
  $class_3 = '.100';
} elseif (5 == $a_c_a_min) {
  $class_3 = '.10';
}

if (7 == $a_c_a_max) {
  $class_4 = '.100';
} elseif (7 == $a_c_a_min) {
  $class_4 = '.10';
}

[...] up to number 6

输出应该是:

 $class_1 = '.50'; (1)
 $class_2 = '.70'; (5)
 $class_3 = '.90'; (7)
 $class_4 = '.60'; (2)
 $class_5 = '.100'; (25)
 $class_6 = '.60'; (2)
 $class_7 = '.80'; (6)

注意:如果值是1,2,1,1,3,那么我想使用.100.90.80 - 从最高开始。

【问题讨论】:

  • $a_c_s是字符串,不是数组,需要用explode()转成数组。
  • 当然,我只是缩短了代码$a_c_a = '1,5,7,2,25,2,6'; AND $a_c_s = explode(',', $a_c_a);

标签: php arrays sorting for-loop


【解决方案1】:

首先使用array_unique() 获取数组的所有不同值,然后使用sort() 对它们进行排序。然后您可以创建一个关联数组,将这些排序后的值映射到相应的百分比。

$percentages = array(100, 90, 80, 70, 60, 50, 40, 30, 20, 10);
$unique_values = array_map('intval', array_unique($a_c_s));
rsort($unique_values);
$percent_map = array_combine($unique_values, array_slice($percentages, 0, count($unique_values)));

foreach ($a_c_a as $val) {
    echo $val . " - " . $percent_map[$val] . "%<br>";
}

【讨论】:

  • @HubertFurka 你在数组上调用explode()。这把其他一切都搞砸了。
  • @HubertFurka 任何时候你有像这样的编号名称的变量,你做错了什么。您应该使用数组。
猜你喜欢
  • 2020-06-14
  • 1970-01-01
  • 2015-10-09
  • 2022-06-11
  • 2012-12-26
  • 2012-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多