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.
Related
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>";
I have a wordpress loop retriving a table like this:
I want to check if the name repeats it self and if so do a sum of partial values to show the total.
On my screenshot the 1st and 3rd rows have the same "nome" so the global value should be 85, can any one tellme how to do this ?
my php :
<?php while( have_rows('wallet_repeater') ): the_row();
echo '<div class="promotoras_item_wallet"> ';
echo '<div class="promnames_wallet"> ';
// vars
$adicionados = get_sub_field('wallet_promotora');
foreach($adicionados as $post) :
$nome = simple_fields_values("pname1");
$im = simple_fields_values("ftotop");
$cp=$adicionados ;
$imatop = $im;
$data=get_sub_field('wallet_data');
$evento=get_sub_field('wallet_evento');
$obs=get_sub_field("wallet_obs");
$numeros_horas = get_sub_field("Wallet_n_horas");
$valor_horas = get_sub_field("wallet_valorh");
$evento = get_sub_field("wallet_evento");
$horarios = get_sub_field("wallet_horario");
$total_parcial = $valor_horas * $numeros_horas."€";
$ii = wp_get_attachment_image($imatop[0]);
?>
<table id="wallet_table1" width="900px" border="0" cellspacing="2" cellpadding="0">
<tbody>
<tr>
<tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';">
<td class="wallet_data_img" width="5"><div class="w_promotora_images"><?php echo wp_get_attachment_image($imatop[0]); ?></td>
<td class="wallet_data_data" width="20"><?php echo the_sub_field('wallet_data'); ?> </td>
<td class="wallet_data_nome" width="200"><?php echo $nome[0];$nomes[]=$nome[0];?></td>
<td class="wallet_data_evento" width="10"> <?php echo the_sub_field("wallet_evento"); ?></td>
<td class="wallet_data_horarios" width="10"><?php echo the_sub_field("wallet_horario"); ?></td>
<td class="wallet_data_obs" width="10"><?php echo the_sub_field("wallet_obs"); ?></td>
<td class="wallet_data_horas" width="10"><?php echo the_sub_field("Wallet_n_horas")."h"; ?></td>
<td class="wallet_data_valorh" width="5"><?php echo the_sub_field("wallet_valorh")."€"; ?></td>
<td class="wallet_data_props" width="5"><?php echo the_sub_field("wallet_props"); ?></td>
<td class="wallet_data_total" width="5">Parcial: <?php echo $total_parcial; ?> global:
</td> </tr></tbody></table>
<?php
Stuff the query data into an associative array and after that output it.
You can do it like that:
$qry = new WP_Query('post_type' => 'your_post_type', 'posts_per_page' => -1)
$arr = array();
while($qry->have_posts()) {
$qry->the_post()
$nam = //Get the name data;
$val = //Get the «global» data;
if($qry[$nam]) {
$qry[$nam]['global'] += $val;
}
else {
$qry[$nam] = array(
'foto' => //Photo data of the current post,
'name' => //Photo data of the current post,
//and so on
'global' => $val,
);
}
}
foreach($qry as $key => $data) {
//Output your table here
}
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>
Have array named for example $data_debit_turnover
Array
(
[0] => Array
(
[VatReturnRowNumberForDebitTurnover] => 63
[Total] => 0.00
)
[1] => Array
(
[VatReturnRowNumberForDebitTurnover] => 64
[Total] => 44.28
)
)
Have HTML that need to look like this
<table><tr>
<td><strong>63</strong></td>
<td>0.00</td>
</tr><tr>
<td><strong>64</strong></td>
<td>44.28</td>
</tr></table>
At first tried with php foreach, but in such case instead of one table get multiple tables [0], [1] etc.
Then tried
<td><strong>64</strong></td>
<td><?php
if( $data_debit_turnover[1][VatReturnRowNumberForDebitTurnover] == '64'){
echo $data_debit_turnover[1][Total]. ' Total<br>';
}?>
</td>
but problem is with [1] etc. I do not know number of []; may be [1] and may be [30].
Tried something like this
$resultVatReturnRowNumberForDebitTurnover = array();
$resultTotal = array();
foreach($data_debit_turnover as $i => $result){
$resultVatReturnRowNumberForDebitTurnover[] = $result[VatReturnRowNumberForDebitTurnover];
$resultTotal[] = $result[Total];
}
<td><strong>64</strong></td>
<td><?php
if (in_array('64', $resultVatReturnRowNumberForDebitTurnover)) {
echo $resultTotal[1];
}?>
</td>
The same problem [1]. How to echo corresponding (index) value from the another array.
For example if 64 is the second value in array $resultVatReturnRowNumberForDebitTurnover then need to echo the second value from array $resultTotal.
Possibly there is some other way.
Please advice.
Showing what I did with foreach
<?php
foreach($data_debit_turnover as $i => $result){
?>
<table>
<tr>
<td><strong>63</strong></td>
<td>
<?php if($result[VatReturnRowNumberForDebitTurnover] = '63') {
echo $result[Total];
} ?>
</td>
</tr>
<tr>
<td><strong>64</strong></td>
<td>
<?php if($result[VatReturnRowNumberForDebitTurnover] = '64') {
echo $result[Total];
} ?>
</td>
</tr>
</table>
<?php
}
?>
Update Thanks to #user2340218 advice get some solution. For each <td> must use foreach. Possibly there is some better solution.
<table><tr>
<td><strong>64</strong></td>
<td><?php foreach($data_debit_turnover as $vatReturn){if($vatReturn['VatReturnRowNumberForDebitTurnover'] == '64') {echo $vatReturn['Total'];}}?></td>
</tr><tr>
<td><strong>67</strong></td>
<td><?php foreach($data_debit_turnover as $vatReturn){if($vatReturn['VatReturnRowNumberForDebitTurnover'] == '67') {echo $vatReturn['Total'];}}?></td>
</tr></table>
Solution Finally used solution #Daniel P advised.
$resultVatReturnRowNumberForDebitTurnover = array();
$resultTotal = array();
foreach($data_debit_turnover as $i => $result){
$resultVatReturnRowNumberForDebitTurnover[] = $result[VatReturnRowNumberForDebitTurnover];
$resultTotal[] = $result[Total];
}
$VatReturnRowNumberForDebitTurnoverModified = array_combine($resultVatReturnRowNumberForDebitTurnover, $resultTotal);
<table>
<tr>
<td><strong>62</strong></td>
<td>
<?php echo $VatReturnRowNumberForDebitTurnoverModified[62]; ?>
</td>
</tr>
<tr>
<td><strong>63</strong></td>
<td>
<?php echo $VatReturnRowNumberForDebitTurnoverModified[63]; ?>
</td>
</tr>
</table>
Actually have to accept #Daniel P answer:) But as understand can not accept 2 answers
I am guessing that VatReturnRowNumberForDebitTurnover numbers are unique so your array should look like this :
Array
(
[63] => 0.00
[64] => 44.28
)
The array index is your VatReturnRowNumberForDebitTurnover and the value is your total.
To test if a VatReturnRowNumberForDebitTurnover has a value your simply use isset()
if (isset($array[63])) {
echo $array[63]
}
Building the table :
<table>
<?php foreach($data_debit_turnover as $i => $total){ ?>
<tr>
<td><strong><?php echo $i; ?></strong></td>
<td><?php echo $total; ?></td>
</tr>
<?php } ?>
</table>
Do you mean this?
<table>
<?php foreach($data_debit_turnover as $vatReturn){ ?>
<tr>
<td><strong><?php print $vatReturn['VatReturnRowNumberForDebitTurnover'] ?></strong></td>
<td><?php print $vatReturn['total'] ?></td>
</tr>
<?php } ?>
</table>
Use foreach like this:
<table>
<?php
foreach ($Array as $item)
{
echo '<tr>';
echo '<td><strong>' . $item['VatReturnRowNumberForDebitTurnover'] . '</strong></td>';
echo '<td>' . $item['Total'] . '</td>';
echo '</tr>'
}
?>
</table>
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>;