php generated table using rowspan - php

I am using this code to generate a table which will subsequently be modified to upload data to a mysql database.
<?php
$start_loc_number= 1 ;
$start_loc_alpha= 'A' ;
$end_loc_number= 10 ;
$end_loc_alpha= 'J' ;
$out = '';
$out .= '<table border = 1 bordercolor="#FF0000">';
for($tr='A';$tr<=$end_loc_alpha;$tr++)
{ $out .= "<tr>";
for($td=1;$td<=$end_loc_number;$td++)
{ $out .= '<td BGCOLOR="#99CCFF">'.$tr.$td.'</td>
<td id="sampleID" contenteditable="true"> sampleID</td>
<td id="volume" contenteditable="true"> volume</td>' ;
}
$out .= "</tr>";
}
$out .= "</table>";
echo $out;
?>
At the moment the table generates 3 cells per iteration in 3 column cells,
| coordinates | sample ID | volume |
My question relates to how the php code can be altered so to generate a table where the coordinates cell can be arranged as a rowspan over the sampleID and volume cells positioned in 2 rows with the sample ID over the volume cell
| | sample ID
| coordinates |------------
| | volume

try this,
for($tr='A';$tr<=$end_loc_alpha;$tr++)
{ $out .= "<tr>";
for($td=1;$td<=$end_loc_number;$td++)
{ $out .= '<td BGCOLOR="#99CCFF">'.$tr.$td.'</td><td>
<table><tr style="border-bottom: 1px solid red">
<td id="sampleID" contenteditable="true"> sampleID</td></tr>
<tr> <td id="volume" contenteditable="true"> volume</td></tr></table></td>' ;
}
$out .= "</tr>";
}

This works for me
<table>
<tr>
<td rowspan="2">test</td>
<td>test1</td>
</tr>
<tr>
<td>test2</td>
</tr>
</table>
EDIT : fiddle

you can set rowspan="2" on your coords TD.
You really should not build your output like that.
Try this approach:
<?php
$content = array(
array(
'cords' => 1,
'samp' => "Bar",
'vol' => 13
),
array(
'cords' => 2,
'samp' => "Foo",
'vol' => 456
),
array(
'cords' => 3,
'samp' => "DJ",
'vol' => 34
)
);
?>
<table>
<tbody>
<? foreach($content as $key => $value) { ?>
<tr>
<th rowspan="2">Coordinates: <?= $value['cords'] ?></th>
<td>sample ID: <?= $value['samp'] ?></td>
</tr>
<tr>
<td>volume: <?= $value['vol'] ?></td>
</tr>
<? } ?>
</tbody>
</table>

Related

PHP loop for calculating averages of values in html table

I have a page on my site that displays multiple html tables. One of these tables houses test values pulled from the database. The last row of this table is calculated by php, which I've been using based on the 8 tests. However, now the tests are not set at 8 so they may sometimes be 4,5 or up to 8 but there's no way to know. I have my PHP loop calculating the average by 8 but I need it to probably base the formula off of an actual count.
The PHp loop in the code below works great if there are values for all 8 tests. As you can see, it divides two row elements, stores that answer and then multiplies it by another. The math is working, I just need help getting it to count rather than using a static number of 8.
Here is the code:
//Table
$query1 = "SELECT * FROM staging";
$result1 = mysqli_query($connect,$query1);
while($row = mysqli_fetch_array($result1)){
?>//PHP loops around entire table
<table style="width:100%; border:none;
border-collapse:collapse;">
<tr style="border:none;">
<th style="border:none; text-align: left;" >Meter Test</th>
<th style="border:none;">Test 1</th>
<th style="border:none;">Test 2</th>
<th style="border:none;">Test 3</th>
<th style="border:none;">Test 4</th>
<th style="border:none;">Test 5</th>
<th style="border:none;">Test 6</th>
<th style="border:none;">Test 7</th>
<th style="border:none;">Test 8</th>
</tr>
<tr style="border: none;" >
<td style="border:none; text-align: left;">Test Rate GPM: </td>
<td><? echo $row['test1TestRateGPM'];?> </td>
<td><? echo $row['test2TestRateGPM'];?> </td>
<td><? echo $row['test3TestRateGPM'];?> </td>
<td><? echo $row['test4TestRateGPM'];?> </td>
<td><? echo $row['test5TestRateGPM'];?> </td>
<td><? echo $row['test6TestRateGPM'];?> </td>
<td><? echo $row['test7TestRateGPM'];?> </td>
<td><? echo $row['test8TestRateGPM'];?> </td>
</tr>
<tr>
<td style="border:none; text-align: left;">Meter Volume: </td>
<td><? echo $row['test1MeterVol'];?> </td>
<td><? echo $row['test2MeterVol'];?> </td>
<td><? echo $row['test3MeterVol'];?> </td>
<td><? echo $row['test4MeterVol'];?> </td>
<td><? echo $row['test5MeterVol'];?> </td>
<td><? echo $row['test6MeterVol'];?> </td>
<td><? echo $row['test7MeterVol'];?> </td>
<td><? echo $row['test8MeterVol'];?> </td>
</tr>
<tr>
<td style="border:none; text-align: left;">Tester Volume: </td>
<td><? echo $row['test1TesterVol'];?> </td>
<td><? echo $row['test2TesterVol'];?> </td>
<td><? echo $row['test3TesterVol'];?> </td>
<td><? echo $row['test4TesterVol'];?> </td>
<td><? echo $row['test5TesterVol'];?> </td>
<td><? echo $row['test6TesterVol'];?> </td>
<td><? echo $row['test7TesterVol'];?> </td>
<td><? echo $row['test8TesterVol'];?> </td>
</tr>
<tr>
<td style="border:none; text-align: left;">Tester Accuracy: </td>
<td><? echo $row['test1Accuracy'];?>% </td>
<td><? echo $row['test2Accuracy'];?>% </td>
<td><? echo $row['test3Accuracy'];?>% </td>
<td><? echo $row['test4Accuracy'];?>% </td>
<td><? echo $row['test5Accuracy'];?>% </td>
<td><? echo $row['test6Accuracy'];?>% </td>
<td><? echo $row['test7Accuracy'];?>% </td>
<td><? echo $row['test8Accuracy'];?>% </td>
<td style="border:none;">Overall</td>
</tr>
<tr>
<td style="border:none; text-align: left;">Corrected Accuracy: </td>
//Previous code only for html tables and the database values being pulled
/////////
//Following code is the loop in question
<?php
$sum=0;
for($i=1; $i<=8; $i++){
if($row["test".$i."TesterVol"] == 0){
$row["test".$i."TesterVol"] = 0.001;
}
$testFormA = $row["test".$i."MeterVol"] / $row["test".$i."TesterVol"];
$testFormB = $testFormA * $row["test".$i."Accuracy"];
$testFinalForm = $testFormB;
$sum += $testFinalForm;
?>
<td><?php echo round($testFinalForm,3) ?>%</td>
<?php }
$average = $sum / 7;
?>
<td><?php echo round($average,5)?>% </td>
</tr>
</table>
UPDATE
Screenshot of the table:
Alright, I have a solution for you.
<?php
// Import existing data structure
$data = [
// Test Rate GPM
test1TestRateGPM => 0.5,
test2TestRateGPM => 5,
test3TestRateGPM => 10,
test4TestRateGPM => 15,
test5TestRateGPM => 25,
test6TestRateGPM => 100,
test7TestRateGPM => 150,
test8TestRateGPM => 0,
// Meter Volume
test1MeterVol => 0,
test2MeterVol => 0,
test3MeterVol => 0,
test4MeterVol => 2.74,
test5MeterVol => 4.95,
test6MeterVol => 15.7,
test7MeterVol => 33.5,
test8MeterVol => 0,
// Tester Volume
test1TesterVol => 0.5,
test2TesterVol => 1,
test3TesterVol => 2,
test4TesterVol => 4.04,
test5TesterVol => 6.7,
test6TesterVol => 20,
test7TesterVol => 40.1,
test8TesterVol => 0,
// Tester Accuracy
test1Accuracy => 1,
test2Accuracy => 1,
test3Accuracy => 1,
test4Accuracy => 1,
test5Accuracy => 1,
test6Accuracy => 1,
test7Accuracy => 1,
test8Accuracy => 0
];
// Make data structure sane...
// One row per test. Each row to contain the relevant fields
// Figure out the lowest and highest indices based on the key names, and the keys we want
$lowIndex = INF;
$highIndex = -INF;
$keys = [];
foreach ($data as $key => $value) {
$matches = [];
if (preg_match('/^test([0-9]+)(.*)$/', $key, $matches)) {
$index = (int) $matches[1];
$lowIndex = min($lowIndex, $index);
$highIndex = max($highIndex, $index);
$keys[] = $matches[2];
}
}
$keys = array_unique($keys);
// Loop through to fix the data
$tests = [];
for ($i = $lowIndex; $i <= $highIndex; $i++) { // Assumes contigous indices!
$test = (object)[];
foreach ($keys as $key) {
$test->{$key} = $data['test' . $i . $key];
}
if ($test->TesterVol) {
$test->CorrectedAccuracy = $test->MeterVol / $test->TesterVol;
}
$tests[] = $test;
}
// Yeah! Now we have some sane data. For example, if you use print_r($tests)...
// Array
// (
// [0] => stdClass Object
// (
// [TestRateGPM] => 0.5
// [MeterVol] => 0
// [TesterVol] => 0.5
// [Accuracy] => 0.5
// [CorrectedAccuracy] => 0
// )
//
// [1] => stdClass Object
// (
// [TestRateGPM] => 5
// [MeterVol] => 0
// [TesterVol] => 1
// [Accuracy] => 5
// [CorrectedAccuracy] => 0
// )
// ...
// Output the table!
echo '<table>';
// Header Row
echo '<thead><tr>';
echo '<th>Test #</th>';
foreach ($keys as $key) {
echo '<th>', htmlspecialchars($key), '</th>';
}
echo '</tr></thead>';
// Main data
echo '<tbody>';
foreach ($tests as $testIndex => $test) {
echo '<tr>';
echo '<td>', htmlspecialchars($testIndex), '</td>';
foreach ($keys as $key) { // Using this original array of keys ensures we stay in-order
echo '<td>', htmlspecialchars($test->{$key}), '</td>';
}
echo '</tr>';
}
echo '<tr><td>Average</td>', str_repeat('<td> </td>', count($keys) - 1), '<td>';
echo array_sum(array_map(function ($test) {
return $test->CorrectedAccuracy;
}, $tests)) / count($tests);
echo '</td></tr>';
echo '</tbody>';
echo '</table>';
Correct your database schema. Once you've done that, this is much simpler.
This code re-works your existing schema so that each test is its own record. Once it's in that format, you can use all the standard mechanisms such as map/reduce to work with the data. You could even do all of that within MySQL.
Other things to note... always use htmlspecialchars() around arbitrary data you output in the context of HTML. You're dealing with numbers today, sure, but some day you might not be and the code doing the outputting should handle this correctly.
Also in one of your edits, you were using $_REQUEST data directly in your query, unsanitized or escaped or anything. Switch to parameterized queries to avoid serious security issues. It's very likely your database has already been hijacked, as bots are always on the internet looking for sites like yours to exploit.
If you really want to have the data going the wrong direction, I'll leave flipping that around as an exercise to the reader. :-) But, post a comment if you have a question.

print html table from php array in particular way

I have a array that is dynamically generated and i am able to manipulate the data and print it in a table but I want to be able to print it differently.
This is what I have been able to do so far:
This is what I want to achieve
As you can see the array has multiple entries and for each entry I would like to create a new table and display the data like so:
There are some keys in the array I would prefer to leave out from being added to the table. the key names are: Id, CreatedDate, Incoming
Here is a short sample of what the array looks like:
[records] => Array
(
[0] => Array
(
[Id] =>
[CreatedDate] => 2016-02-18T02:24:57.000Z
[FromName] => Technical Support
[Incoming] =>
[MessageDate] => 2016-02-18T02:24:57.000Z
[Subject] => this is a test reply
[TextBody] => testt ref:_00D708cJQ._50080oYTuD:ref
[ToAddress] => outa#gmail.com
)
[1] => Array
(
[Id] =>
[CreatedDate] => 2016-02-17T13:36:52.000Z
[FromName] => Technical Support
[Incoming] => 1
[MessageDate] => 2016-02-17T13:36:08.000Z
[Subject] => MySupport Portal: Test Email via API
[TextBody] => this is a test email 4 ref:_00D708cJQ._50080oYTuD:ref
[ToAddress] => outa#gmail.com
)
Here is my current php code
$count = $response_array['size'] -1;
//print table headers
echo '<table border=1><tr>';
foreach( $response_array['records'][0] as $key => $value ) {
if($key !== 'Id') {
echo '<th>'.$key.'</th>';
}
}
echo '</tr><tr>';
//print table data
for ($i = 0; $i <= $count; $i++) {
foreach( $response_array['records'][$i] as $key => $value ) {
if($key !== 'Id') {
if($key === 'TextBody') {
echo '<td><pre>'.$value.'</pre></td>';
} else {
echo '<td>'.$value.'</td>';
}
}
}
echo '</tr><tr>';
}
echo "</tr></table>";
I know how to write the HTML but not sure how to tie in the php as im not sure how i can sort the headers to be in different part of the table.. in any case here is the html with dummy data as placeholders
<table border=1>
<tr>
<th>MessageDate</th>
<th>FromName</th>
<th>ToAddress</th>
</tr><tr>
<td>data</td>
<td>data</td>
<td>data</td>
</tr><tr>
<th colspan=3>Subject</th>
</tr><tr>
<td colspan=3>this is the subject</td>
</tr><tr>
<th colspan=3>TextBody</th>
</tr><tr>
<td colspan=3>this is the body</td>
</tr>
</table>
Okay, since you said you are able to do it for 1 line lets show you how to do it for all the line.
Just loop thourgh all the line like this.
<?php foreach( $response_array['records'] as $records): ?>
<table border=1>
<tr>
<th>MessageDate</th>
<th>FromName</th>
<th>ToAddress</th>
</tr><tr>
<td><?php echo $records['MessageDate'] ?></td>
<td><?php echo $records['FromName'] ?></td>
<td><?php echo $records['ToAddress'] ?></td>
</tr><tr>
<th colspan=3>Subject</th>
</tr><tr>
<td colspan=3><?php echo $records['Subject'] ?></td>
</tr><tr>
<th colspan=3>TextBody</th>
</tr><tr>
<td colspan=3><?php echo $records['TextBody'] ?></td>
</tr>
</table>
<?php endforeach; ?>
edit: Added php tags
Unex's answer is perfect. Here is another alternative:-
echo '<table border=1>';
foreach( $response_array['records'] as $key => $value ) {
if($key == 'MessageDate'){
echo "<tr>";
echo "<th>MessageDate</th>";
echo "<th>FromName</th>";
echo "<th>ToAddress</th>";
echo "</tr>";
echo "<tr>";
echo "<td>{$response_array['records'][$key]['MessageDate']}</td>";
echo "<td>{$response_array['records'][$key]['FromName']}</td>";
echo "<td>{$response_array['records'][$key]['ToAddress']}</td>";
echo "</tr>";
}
if($key == 'Subject'){
echo '<tr>';
echo "<th colspan='3'>Subject</th>";
echo "</tr>";
echo '<tr>';
echo "<td colspan='3'>{$response_array['records'][$key]['Subject']}</td>";
echo "</tr>";
}
if($key == 'TextBody'){
echo "<tr>";
echo "<th colspan='3'>TextBody</th>";
echo "</tr>";
echo "<tr>";
echo "<td colspan='3'>{$response_array['records'][$key]['TextBody']}</td>";
echo "</tr>";
}
}
echo "</table>";

Codeigniter explode to html table

I'm currently having issue explode to html table.
My Controller
public function idp_test()
{
$this->load->model('groups/groups_model');
$scholar_id = $this->session->userdata('scholar_id');
$groups = $this->groups_model->retrieve_groups_idp($this->scholar->level_id);
$content = array(
'groups' => $groups,
'scholar' => $this->scholar,
'page_title' => 'My individual development plan',
'page_view' => 'scholar/activities/idp_test',
'page_scripts_view' => 'scholar/inc/_choose_activities_scripts',
'sidebar_menu' => 'idp test'
);
$this->load->view("theme/base", $content);
}
My Model
public function retrieve_groups_idp($level_id)
{
$this->db->select("groups.*, levels.name as levelname");
$this->db->join('activities', 'groups.activity_ids = activities.activity_id' );
$this->db->join('levels', 'levels.level_id = groups.level_id', 'left' );
$this->db->join('activity_types', 'activities.activity_type_id = activity_types.activity_type_id', 'left' );
$this->db->where('groups.level_id', $level_id);
$this->db->group_by('groups_name');
$this->db->order_by('groups_name');
$qr = $this->db->get('groups');
return $qr->result();
}
public function retrieve_activity_desc($activity_ids)
{
$activity_desc_arr[] = explode(', ', $activity_ids);
foreach ($activity_desc_arr as $activity_id){
$this->db->select("activity_id as activityid, CONCAT(activities.name, ' - ', activity_types.name) AS description", FALSE);
$this->db->join('activity_types', 'activities.activity_type_id = activity_types.activity_type_id');
$this->db->where_in('activities.activity_id', $activity_id);
$qr = $this->db->get('activities');
return $qr->result();
}
}
My View
<?php foreach ($groups as $groups): ?>
<table class="table table-vcenter">
<thead>
<tr class="active">
<th><?php echo $groups->groups_name?></th> <!--Series Header -->
<th class="text-center"><small><strong>Module Type</strong></small></th>
<th class="text-center"><small><strong>Status</strong></small></th>
<th class="text-center"><small><strong>Action</strong></small></th>
</tr>
</thead>
<tbody>
<tr>
<td><?php
$rows = $this->groups_model->retrieve_activity_desc($groups->activity_ids);
foreach ($rows as $row){
echo var_dump($row->description);
}
?></td>
<td class="text-center">belom lagi</td>
<td class="text-center">TO ATTEND</td>
<td class="text-center">View Session</td>
</tr>
</tbody>
</table>
<?php endforeach ?>
i can't post images, so below are some sample in view so far
SERIES 1 FOR FS | MODULE TYPES | STATUS | ACTION
Series 1 - FILSeries 1 - CBLSeries 1 - PEL | belom lagi | to attend |
and what i need to achieve is like below sample in view
SERIES 1 FOR FS | MODULE TYPES | STATUS | ACTION
Series 1 - FIL | belom lagi | to attend |
Series 1 - CBL | belom lagi | to attend |
Series 1 - PEL | belom lagi | to attend |
I'm newbie with php & codeigniter, sorry with my english.
Thanks
Think about what you have in your view code:
<tr>
<td><?php
foreach($rows as $row){
var_dump($row->description);
}
?>
</td>
<td>belom lagi</td>
<td>to attend</td>
</tr>
Of course this will all be printed into one table cell, how it could produce anything else, right?
What you need is something like this:
<?php
foreach($rows as $row){
echo "<tr>"; // you need a new row for every entry
echo "<td>".$row->description."</td>";
echo "<td>belom lagi</td>";
echo "<td>to attend</td>";
echo "</tr>";
}
?>
After a few studies, i figured it out, just want to share with everybody.
EDITED - Controller
public function idp_test()
{
$this->load->model('groups/groups_model');
$this->load->model('activities/activity_type_model');
$scholar_id = $this->session->userdata('scholar_id');
$groups = $this->groups_model->retrieve_groups_idp($this->scholar->level_id);
foreach ($groups as $group) {
$act_desc = $this->groups_model->retrieve_activity_desc($group->activity_ids);
$group->activity_ids = $act_desc;
}
EDITED - View
<!-- START TABLE HEADER -->
<?php foreach ($groups as $group): ?>
<table class="table table-vcenter">
<thead>
<tr class="active">
<th><?php echo $group->groups_name?></th> <!--Series Header -->
<th class="text-center"><small><strong>Module Type</strong></small></th>
<th class="text-center"><small><strong>Status</strong></small></th>
<th class="text-center"><small><strong>Action</strong></small></th>
</tr>
</thead>
<tbody>
<?php foreach ($group->activity_ids as $session): ?>
<tr>
<td><?php echo $session->description; ?></td>
<td class="text-center"><?php echo $session->modulename; ?></td>
<td class="text-center">STATUS</td>
<td class="text-center">View Session</td>
</tr>
<?php endforeach ?>
</tbody>
</table>
<?php endforeach ?>
<!-- END 1 -->
Come out as what i need.
Thank you stackoverflow.

html table and populate with php with empty rows

I am trying to fill table with data.
I want to achieve something that looks like
However, my result is:
I guess this might be related to the php IF-statement.
Here is my code:
<table class="tg">
<tr>
<th class="tg-s6z2" colspan="2" rowspan="4">OPPONENT</th>
<th class="tg-s6z2" colspan="5">DIVISION</th>
</tr>
<tr>
<td class="tg-s6z2" colspan="5">TEAM</td>
</tr>
<tr>
<?php
foreach($rows as $row) {
echo "<td class='tg-031e' colspan='2'>";
echo $row["Date"];
echo "</td>";
}
?>
</tr>
<tr>
</tr>
<?php
foreach($rows as $row) {
echo"<tr>";
echo "<td class='tg-031e' colspan='2'>";
echo $row["teamName"];
echo "</td>";
if(!empty($row["Score"])){
echo"<td>";
echo$row["Score"];
echo "</td>";
}else{
echo "<td> </td>";
}
echo"</tr>";
}
?>
</table>
THE OUTPUT OF $results
Array (
[0] => Array (
[Date] => 2015-04-22
[0] => 2015-04-22
[Score] => 1:4
[1] => 1:4
[divisionID] => 2
[2] => 2
[3] => 2
[teamName] => TEAM YXZ
[4] => TEAM XYZ )
[1] => Array (
[Date] => 2015-04-15
[0] => 2015-04-15
[Score] => 2.5:2.5
[1] => 2.5:2.5
[divisionID] => 2
[2] => 2
[3] => 2
[teamName] => TEAM XYZ 'B'
[4] => TEAM XYZ 'B'
)
)
You need to loop over the dates of the column headings, checking whether the current element of $rows matches the corresponding date. First make an array of all the dates when you're creating the headings:
$dates = array();
foreach($rows as $row) {
echo "<td class='tg-031e' colspan='2'>";
echo $row["Date"];
$dates[] = $row['Date'];
echo "</td>";
}
Then when you write the rows, loop through the dates. When it matches, write the score, otherwise leave the <td> empty (there's no need to write ).
foreach($rows as $row) {
echo"<tr>";
echo "<td class='tg-031e' colspan='2'>";
echo $row["teamName"];
echo "</td>";
foreach ($dates as $date) {
echo "<td>";
if ($row['Date'] == $date && !empty($row['Score'])) {
echo $row["Score"];
}
echo "</td>";
}
echo"</tr>";
}
Your conditional statement checking $row['score'] is saying add a TD with a score or add a TD with nothing. You still need to add a TD regardless if it's blank or not or it will break the table layout.
Also, the data you get back, is it enough data for the loop to fill out the whole table? It seems to me that there is something going on with the data being returned along with the conditional statement.
The example image you gave is not corresponding with the data $rows has. The match on 2015-04-22 should have the score 1:4 right?
I've separated the logic from the HTML.
In my opinion, the way $rows is constructed is generally bad design.
With that in mind; here's what I've came up with;
<?php
$dates = array();
foreach ($rows as $row):
$dates[] = $row['Date'];
endforeach;
$matches = array();
foreach ($rows as $row):
$scores = array();
foreach ($dates as $date):
$score = '';
if (!empty($row['Score']) && $row['Date'] === $date):
$score = $row['Score'];
endif;
$scores[] = $score;
endforeach;
$matches[] = array('teamName' => $row['teamName'], 'Scores' => $scores);
endforeach;
?>
<table class="tg">
<tr>
<th class="tg-s6z2" colspan="2" rowspan="4">OPPONENT</th>
<th class="tg-s6z2" colspan="5">DIVISION</th>
</tr>
<tr>
<td class="tg-s6z2" colspan="5">TEAM</td>
</tr>
<tr>
<?php foreach ($dates as $date): ?>
<td>
<?php echo $date; ?>
</td>
<?php endforeach; ?>
</tr>
<tr>
</tr>
<?php foreach ($matches as $match): ?>
<tr>
<td class="tg-031e" colspan="2">
<?php echo $match['teamName']; ?>
</td>
<?php foreach ($match['Scores'] as $score): ?>
<td><?php echo $score; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>

Seperate comma separated mySql database field value with php

If you believe this is a duplicate please let me now as I'm not totally sure what to search for to check, (I will remove if duplicate)
I have a list of of numbers in a mySql field called sess_times in a table called test_sess, the numbers for the first row are:
25, 38, 40, 50
is it possible to split these into php variable e.g:
$no1 = 25
$no2 = 38
$no3 = 40
$no4 = 50
I'm trying to put the individual numbers in a table, something like below:
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td> 1 </td>
<td><?php echo $no1; ?></td>
</tr>
<tr>
<td> 2 </td>
<td><?php echo $no2; ?></td>
</tr>
<tr>
<td> 3 </td>
<td><?php echo $no3; ?></td>
</tr>
<tr>
<td> 4 </td>
<td><?php echo $no4; ?></td>
</tr>
</table>
Any help with this would be great so thanks in advance for any answers.
HERE'S THE SOLUTION I USED, A COMBINATION OF 2 ANSWERS BELOW:
$data = '25,38,40,50';
$string = explode(",", $data);
$number = 0;
echo '<table cellspacing="0" cellpadding="0" border="0">';
for($i=0; $i<count($string); $i++)
{
$number = $number +1;
echo '
<tr>
<td>' . $number . '</td>
<td>' . $string[$i] . '</td>
</tr>
';
}
You can use PHP's explode function.
When you output everything, save it into a variable.
Then, $string = explode(",", $string); will produce this:
Array ( [0] => 28[1] => 38 [2] => 40 [3] => 50 )
To output this, you can then use $string[number] for each value.
You can explode them
$string="25,38,40,50";
$numbers=explode(",",$string);
print_r($numbers); // You can use them for printing like echo $numbers[0]; or 1 or 2 or 3
And if you don't want the result in an array and still want those 4 variable names you can do this
$string="25,38,40,50";
list($no1,$no2,$no3,$no4)=explode(",",$string);
This would give you the table output and it doesn't require the total amount to be known.
$data = '25,38,40,50';
$arr = explode(',', $data);
echo '<table cellspacing="0" cellpadding="0" border="0">';
for($i=0; $i<count($arr); $i++)
{
echo '
<tr>
<td>' . $i+1 . '</td>
<td>' . $arr[$i] . '</td>
</tr>
';
}
echo '</table>';
Use explode();
ex:
$numbers='25,38,40,50';
$numbers_array= explode(",", $no);
foreach($numbers_array as $key => $number)
{
$var_name='no'.(++$key);
$$var_name=$number;
}
echo $no1.'<br>;
echo $no2.'<br>;
echo $no3.'<br>;
echo $no4.'<br>;

Categories