简体   繁体   中英

How to change font colour based on ID number from output

so I have a JSON url that I am pulling post titles from and that all works, but what I want to do is have it so that depending on the userID, determines what colour the post would be, so for example if the userID is 1 then make the font colour red.

$data = file_get_contents($json_url); 
$posts = json_decode($data);

foreach ($posts as $post) {

echo $post->title . '<br>';
 }

Wrap your title in a <span> or <div> and give it a class related to the userId:

foreach ($posts as $post) {
  echo sprintf('<span class="titleUser%d">%s</span>', $post->userId, $post->title);
}

(assuming $post->userId is your userId, change this to fit your needs)

You'll end up with different classes like titleUser1 , titleUser27 etc.

Define the styles for the classes you want to change in your CSS:

.titleUser1 {color: red}
.titleUser27 {color: green}

No need to create if clauses for every user, just add a new class to your style when needed.

Try this:

foreach ($posts as $post) {
if($post->userId == 1){
    echo "<div style='color:red'>".$post->title ."</div><br>";
    }
elseif ($post->userId == 1){
    echo "<div style='color:blue'>".$post->title ."</div><br>";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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