Can I make a div change its background color based

2019-07-18 12:00发布

I have a PHP index page where data from an array is being displayed inside <div>'s on top of a picture. I want the <div>'s to change color based on the content inside it.

The idea is this:

I have Customer   -    Date    -    Due in

The array I mean has a structure like the following:

Array(
   [0] => array('customer' => 'John', 'date' => '2012-05-11', 'due' => 9),
   [1] => array('customer' => 'Hess', 'date' => '2011-12-11', 'due' => 5),
   [2] => array('customer' => 'Mrac', 'date' => '2012-06-18', 'due' => 3)
)

Due in shows a number of days - I want the <div> to be red if the number inside it is 5 or lower.

Any help would be greatly appreciated.

3条回答
家丑人穷心不美
2楼-- · 2019-07-18 12:42

Within the php code, give the div a different class if "Due in" is less than or equal to 5. So in your PHP, when you're looping through your array:

<?php 
  echo "<div";
  if($myArray[i]['due'] <= 5){ echo " class='dueSoon'"; }
  echo "> $myArray[i]['customer'] - $myArray[i]['date'] - $myArray[i]['due'] </div>";
?>

so that the following gets output when there's less than 5 days:

<div class="dueSoon"> ... </div>

And then css:

.dueSoon { background-color:red; }
查看更多
别忘想泡老子
3楼-- · 2019-07-18 12:44

We will suppose that your array is named as results

CSS

.red{
background-color: red;
}

The following is the PHP code that you have to use to print out this array.

<?php foreach ($results as $result){?>
<div class="<?php if ($result['due'] < 5 || $result['due'] == 5) echo '.red';?>">
 Customer: <?php echo $result['customer']; ?>
 Date: <?php echo $result['date'];?>
 Due: <?php echo $result['due']; ?>
</div>
<?php } ?>
查看更多
Summer. ? 凉城
4楼-- · 2019-07-18 12:51

In your PHP code, check for this condition, if the condition is being met, then add a css class to that div (for which the condition is being satisfied).

Define the CSS class in your CSS file.

查看更多
登录 后发表回答