如何根据数组中的值更改表中td的背景颜色

时间:2017-10-31 14:46:20

标签: javascript php html arrays

我需要有关此代码的帮助..

这是表格:

<table id="tabela_zaduzi_plombe" class="table-responsive table table-striped table-bordered table-hover dataTable no-footer font-size-13">
  <thead>
    <tr class="boja-reda">
      <th class="width-50"></th>
      <th class="align-center width-50"><input type="checkbox" id="checkAll" /></th>
      <th class="width-300"><?php echo __("SERIJSKI BROJ"); ?></th>

    </tr>
  </thead>
  <tbody>
  <?php //debug($lista_slobodnih_plombi); die; ?>
  <?php foreach($lista_slobodnih_plombi as $lista_sp): ?>
    <?php foreach($lista_sp as $lista): ?>
    <tr>
      <td></td>
      <td class="align-center td_checkbox"><input type="checkbox"  name="link-cbx" class="checkItem" autocomplete="on" id="<?php echo $lista;?>" data-sb_plombe="<?php echo $lista;?>"/></td>
      <td class="sbr"><?php echo $lista;?></td>

    </tr>

    <?php endforeach; ?>
  <?php endforeach; ?>

  </tbody>
</table>

这是数组的输出:

    array(
    (int) 0 => array(
        (int) 0 => '222222222',
        (int) 1 => '222222223',
        (int) 2 => '222222224',
        (int) 3 => '222222225'
    ),
    (int) 1 => array(
        (int) 0 => '333333333',
        (int) 1 => '333333334'
    ),
    (int) 2 => array(
        (int) 0 => '444444444',
        (int) 1 => '444444445',
        (int) 2 => '444444446',
        (int) 3 => '444444447',
        (int) 4 => '444444448'
    )
)

我需要更改背景颜色,以便数组的每个成员都有自己的颜色。

示例:如果我有3个阵列,我需要3种不同的颜色。 谢谢!

1 个答案:

答案 0 :(得分:0)

在向td添加背景颜色之前,需要为每个数组键生成随机颜色。这是使用键和值(颜色代码)

创建颜色数组的功能
function getColors($array) {
        // init array
        $colors = array();
        // count of number of random colors to generate
        if(count($array)>0){
            // get the keys of passed array ( will be help full if the passed array is associative array )
            $array_keys = array_keys($array);
            $chars = "ABCDEF0123456789";
            $size = strlen($chars);
            foreach($array_keys as $value){
                for( $j = 0; $j < 6; $j++ ) {
                    // generate a random color for each key of passed array
                    $colors[$value] .= $chars[ rand( 0, $size - 1 ) ];
                }
            }
        }
        return $colors;
    }

现在为td添加bgcolor。

<?php 
   // call the function to get random colors
    $colors = getColors($lista_slobodnih_plombi);?>

  <?php foreach($lista_slobodnih_plombi as $key=>$lista_sp): ?>
    <?php foreach($lista_sp as $lista): 

    ?>
    <tr>
      <td></td>
      <td class="align-center td_checkbox"><input type="checkbox"  name="link-cbx" class="checkItem" autocomplete="on" id="<?php echo $lista;?>" data-sb_plombe="<?php echo $lista;?>"/></td>
      <td class="sbr" bgcolor="<?php echo '#'.$colors[$key];?>"><?php echo $lista;?></td>

    </tr>

    <?php endforeach; ?>
  <?php endforeach; ?>

注意:每次加载页面时背景颜色都会发生变化。