简体   繁体   English

Select 基于来自另一个数组的二进制值的一个或多个数组值

[英]Select one or more values from an array based on binary value(s) from another array

I have two arrays.我有两个 arrays。 COLORS and STATUS (based on a binary string). COLORS 和 STATUS(基于二进制字符串)。

$binary_string = '001'; // Can be any combination of 0 and 1 (000,111,100,etc)
$colors = array('red','green','blue');
$status = str_split($binary_string);

I need to return the active/selected color(s) based on the string.我需要根据字符串返回活动/选定的颜色。 In the example, I should get "blue".在这个例子中,我应该得到“蓝色”。 What is the easiest way to achieve this in PHP?在 PHP 中实现这一目标的最简单方法是什么? An example, please.请举个例子。

Thanks!谢谢!

Simply you need loop over status array which binary string representation of color if find 1 will set color to corresponding color in RGB and just exit the loop!只需遍历status数组,如果 find 1color的二进制字符串表示设置为RGB中的相应颜色,然后退出循环!

<?php
$binary_string = '001';
$colors = array('red','green','blue');
$status = str_split($binary_string);

$color = '';
foreach ($status as $i => $bin) {
    if($bin==='1'){
        $color = $colors[$i];
        break;
    }
}
echo $color;//blue
?>

I think you want something like this:我想你想要这样的东西:

<?php
$binary_string = '101'; // Can be any combination of 0 and 1 (000,111,100,etc)
$colors = array('red','green','blue');
$status = str_split($binary_string);
$final_colors = "";
for ($i=0; $i< 3; $i++) {
    SWITCH($i) {
        case 0:
         $final_colors .= $status[$i] ? 'red, ' : '';
         break;
        case 1:
         $final_colors .= $status[$i] ? 'green, ' : '';
         break;
        case 2:
         $final_colors .= $status[$i] ? 'blue' : '';
         break;
    }
}

echo $final_colors;

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

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