简体   繁体   中英

If statement inside foreach loop to format specific column

This is my current code to fetch the data:

<thead>
<?php
foreach ($fields as $val) {
$fieldname=$val->name;
echo "<th>".$fieldname."</th>";
}
?>
</thead>

<tbody>
<tr>
<?php
foreach ($rows as $data){       
echo "<td>".$data."</td>";
?>
</tr>
</tbody>

Some of the fields are Id, Title, Amount, and so on. I would like to format the specific column 'Title' so it will become a link. Thank you very much.

I tried If Statements like:

if($rows==$rows['AMOUNT']){
//format here
}

but it yields no advancement. The If Statement works, however, with the fieldnames if I want to,say, change the font-style of a single column.

As you mentioned in comment $rows is Associative array

in your case you need to get both array value and array key the foreach syntax of getting key and value is

foreach($array as $key => $value)

try with this checking the key of array and you can use elseif also if you want to make check on another field

foreach ($rows as $key => $data)
{       
   if($key == 'Title'){
     echo "<td><a href='yourlink'>".$data."</a></td>";
   }
   else{
     echo "<td>".$data."</td>";
   }
}

if you use associative array check key value to identify column:

<?php
foreach ($rows as $key => $data){ 
    if($key == 'AMOUNT')
        //format here
    elseif($key == 'TITLE')
        //format here
    else
        echo "<td>".$data."</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