简体   繁体   中英

Calling a switch case function from inside HTML

I am having problems trying to use a switch case to display an image if the tank_id matches the case string.

Here is my code:

...//
<?php foreach ($tank_stats['data']['1076056102'] as $key => $value) { ?>               
    <tr>
      <td><?php echo tank_IDs();?></td> //should display the correct tank image depending on what tank_id string in JSON

      <td><?php echo number_format($value['all']['battles']); ?> </td>
      <td><?php echo number_format($value['all']['wins']); ?> </td>
      <td><?php echo number_format($value['all']['losses']); ?> </td>
      <td><?php echo number_format($value['all']['frags']); ?> </td>  
    </tr>
<?php } ?> 
 ...//

<?php function tank_IDs () {
  switch ($tank_stats['tank_id']) {
      case "3649":
        echo '<img class="tanks" src="tank_1.png"/>';
        break;

      ...//

      default:
        echo '<img class="tanks" src="tank_2.png"/>';
 }
}
?>

What I want is to call my switch case function 'tank_IDs' inside the in my table, and if the tank_id matches the tank JSON data, it displays the correct image.

So in my first case, if tank_id is "3649" it should display the correct tank pic. At the moment, it is displaying the 'default' case image in my case function.

Am I missing something obvious?

You need to make the ID available to the function.

You could also change the echo 's to return 's as you are using an echo in the <td><?php echo tank_IDs($tank_stats['tank_id']); ?></td> <td><?php echo tank_IDs($tank_stats['tank_id']); ?></td> and it is always better to return data from a function rather than have the function generate output itself.

function tank_IDs ($tankId) {
  switch ($tankId) {
      case "3649":
        return '<img class="tanks" src="tank_1.png"/>';


  //...

      default:
       return '<img class="tanks" src="tank_2.png"/>';
 }
}

Usage:

<td><?php echo tank_IDs($tank_stats['tank_id']); ?></td>

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