Как следовать номеру префикса согласно таблице, содержащей значение, чтобы изменить цвет показа на странице? - PullRequest
0 голосов
/ 21 апреля 2020

Я создал таблицу для отображения данных из таблицы базы данных на странице. Моя проблема заключается в том, как следовать номеру префикса в соответствии с таблицей, содержащей значение, чтобы изменить отображение цветов на странице?

Ниже приведен мой вывод: output

Ниже моя кодировка:

<tbody>
                            <?php
                            $sql_wtp = "select * from  filing_code_management";
                            $query_wtp = db_conn_select($sql_wtp);
                            foreach ($query_wtp as $rs_wtp) {
                                if ($rs_wtp['status'] == 1) {
                                    $active = 'Active';
                                } elseif ($rs_wtp['status'] == 0) {
                                    $active = 'Inactive';
                                }
                                echo "<tr>";
                                echo "<td>" . (++$no) . "</td>";
                                echo "<td>" . $rs_wtp['name'] . "</td>";
                                echo "<td>" . $rs_wtp['folder_location'] . "</td>";
                                echo "<td>" . $rs_wtp['category'] . "</td>";
                                echo "<td>" . $rs_wtp['request_by'] . "</td>";
                                echo "<td>" . $rs_wtp['date_request'] . "</td>";
                                echo "<td>" . $active . "</td>";
                                if ($module_user_permission['edit'] == 1) {
                                    echo '<td><a href="#wtp_modal" onclick="select_(\'' . md5($rs_wtp['id'].$md5) . '\',\'wtp_content\')" data-toggle="modal" data-original-title="Help" class="btn btn-sm btn-primary" data-color-format="hex">Update</a>';
                                    if ($rs_wtp['status'] == 1) {
                                            echo '<a onclick="delete_(\'' . md5($rs_wtp['id'].$md5) . '\',1)" class="btn btn-sm btn-primary" data-color-format="hex">Deactivate</a>';
                                        } elseif ($rs_wtp['status'] == 0) {
                                            echo '<a onclick="delete_(\'' . md5($rs_wtp['id'].$md5) . '\',0)" class="btn btn-sm btn-primary" data-color-format="hex">Activate</a>';
                                        }
                                    echo '</td>';
                                }
                                echo "</tr>";
                            }
                            ?>
                        </tbody>

Я хочу, чтобы номер префикса следовал ниже номера диапазона:

Prefix number |      Color 
--------------------------
100 until 199 |      Blue
200 until 299 |      Red
300 until 399 |      Yellow
400 until 499 |      Orange
500 until 599 |      Green

На самом деле я хочу, чтобы вывод был таким же, как под образцом изображения, под изображением образца я не использую кодирование, просто я использую программное обеспечение для рисования, чтобы отредактировать и сделать так, чтобы вам было понятно, что я хочу получить:

Output 2 Надеюсь, кто-то сможет направь меня или дай мне несколько идей, чтобы это сработало. Спасибо.

1 Ответ

1 голос
/ 21 апреля 2020

Я вижу пару постоянных вещей в вашей проблеме.

  1. Все ваши подкатегории начинаются с цифры, ie: 100, 200, 300, 300-1, et c ...
  2. У вас есть правило, которое устанавливает числовые значения в качестве потенциального индекса для значений цвета, которые соответствуют этим значениям. ie: 100-199 = синий, 200-299 = красный и т. Д. c ...

Вы можете использовать скобку в конце вашей переменной, чтобы получить первый символ вашего строка. Таким образом, с учетом сказанного, зная, что ваши значения для каждого цвета попадают в числа c, которые содержат константу, причем первое число в строке чисел одинаково, ie: 100, или 102, или 134, или 178, или 199, все они всегда синего цвета, вы можете использовать этот метод, чтобы получить первый символ вашей строки ($ variable) и сравнить его с массивом потенциальных значений цветов с ключами, установленными для соответствующих правил для индекса цвета.

См. Мой пример ниже:

$valuetocheck = "299-45 PENTADBIRAN"; // --> I believe this would be $rs_wtp['name'] correct?

//--> This can be placed anywhere on the page above the foreach loop
$colors = array (
    "1" => "blue",   //--> for all colors within the range of 100-199
    "2" => "red",    //--> for all colors within the range of 200-299
    "3" => "yellow", //--> for all colors within the range of 300-399
    "4" => "purple", //--> for all colors within the range of 400-499
    "5" => "green"   //--> for all colors within the range of 500-599
);
$stmt = null; //--> NULL variable to hold the concatenated values and display in your echo

//--> place the following foreach loop right after you define `$rs_wtp`, 
foreach($rs_wtp['name'] as $name => $valuetocheck){
    //--> Get the first character of the string, which will be the number that id's the color
    $check = $valuetocheck[0];
    //--> start the div that will style your text, or set a class            
    $stmt .= '<div style="color:'; 
    //--> Iterate over the color array to find the right color
    foreach ($colors as $key => $color){ 
        //--> compare the first character against the $key value 
        //--> within $colors array each iteration through the $rs_wtp array
        if($check == $key){
            $stmt .= $color;  //--> Concatenate $stmt 
        }
    }$stmt .= ';">'.$valuetocheck.'</div>'; //--> Close style attribute and div tag
}

echo $stmt; //-> place this in the <td> tag that holds the `$rs_wtp['name'] in  your code`

Fiddle: http://sandbox.onlinephpfunctions.com/code/9938a5e6a88de29511d22458a23a39b3a2368995

РЕДАКТИРОВАТЬ 4/22 / 20:

Поместите следующее определение, мы определим массив цветов и превратим его в константу, чтобы область действия была глобальной.

Затем создайте функцию, которая будет выполнять итерацию по вашему names и folder_locations и поместите их в стилизованный тег span, затем поместите тег span в блок echo для каждого элемента соответственно.

// the following constant will now be global again place this and the function above your query or in a defines page if you use one.

define("COLORS", array(
    1 => "blue",   //--> for all colors within the range of 100-199
    2 => "red",    //--> for all colors within the range of 200-299
    3 => "yellow", //--> for all colors within the range of 300-399
    4 => "purple", //--> for all colors within the range of 400-499
    5 => "green")   //--> for all colors within the range of 500-599    
);  

function changeColor($value){
    $stmt = null;
    $rs_wtp_name = $value; 
    $check = $rs_wtp_name[0]; // get the first character in the string
    foreach (COLORS as $key => $color){ 
        //--> compare the first character against the $key value 
        //--> within $colors array each iteration through the $rs_wtp array
        if($check == $key){
            $stmt .= $color;  //--> Concatenate $stmt 
        }
    }

    $output = "<span style='color:".$stmt.";'>" . $rs_wtp_name . "</span>";
    return $output;
}

Теперь в вашем коде ... Это должно работать для вас, как ваш код написан. Я не могу проверить ваш запрос, хотя.

 $sql_wtp = "select * from  filing_code_management";
 $query_wtp = db_conn_select($sql_wtp);
      foreach ($query_wtp as $rs_wtp) {
           if ($rs_wtp['status'] == 1) {
                $active = 'Active';
           } elseif ($rs_wtp['status'] == 0) {
                $active = 'Inactive';
           }
           echo "<tr>";
           echo "<td>" . (++$no) . "</td>";
           echo "<td>" . changeColor($rs_wtp['name']) . "</td>";//<- here
           echo "<td>" . changeColor($rs_wtp['folder_location']) . "</td>";//<-- here
           echo "<td>" . $rs_wtp['category'] . "</td>";
           echo "<td>" . $rs_wtp['request_by'] . "</td>";
           echo "<td>" . $rs_wtp['date_request'] . "</td>";
           echo "<td>" . $active . "</td>";
...