php get the same index values from two arrays (outside foreach) - php

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>

Related

only display first column?

This code shows every info from an XML. I want to only display row number one (first from/to, symbol temperature etc)
<?php
$url = ('https://www.yr.no/sted/Norge/oslo/oslo/oslo/varsel_time_for_time.xml');
$feed = simplexml_load_file($url) or die('Can not connect to server');
$result = array();
foreach ($feed->forecast->tabular->time as $content) {
array_push($result, [ "from" => (string)$content['from'],
"to" => (string)$content['to'],
'symbol' => (string)$content->symbol['name'],
'symbol-icon' => (string)$content->symbol['var'],
'temperature' => (string)$content->temperature['value'],
'windDirection' => (string)$content->windDirection['name'],
'windSpeed' => (string)$content->windSpeed['mps'],
'windType' => (string)$content->windSpeed['name'],
]);
}
?>
<button class="collapsible"><div class="tbl-content">
<table cellpadding="0" cellspacing="0" border="0">
<tbody>
<?php foreach ($result as $value) { ?>
<tr>
<td>Oslo</td>
<td><?php echo date("j. M", strtotime($value['from'])); ?> kl.<?php echo date("G", strtotime($value['from'])); ?></td>
<td><img src="http://yr.github.io/weather-symbols/png/100/<?php echo $value['symbol-icon'];?>.png" /></td>
<td><?php echo $value['temperature'] ?> °C</td>
<td><?php echo $value['windType'] ?>, <?php echo $value['windSpeed'] ?> m/s fra <?php echo $value['windDirection'] ?></td>
<td>Longtherm</td>
<td>Hour</td>
</tr>
<?php } ?>
</tbody>
</table>
</div></button>
quite unexperienced, any help is greatly appreciated
Just one of the rows? Remove the foreach! Just use $result[0] in place of $value. :-)
A defined number of rows? Use a for loop:
for ($x = 0; $x < $limit; $x++) {
$value = $result[$x];
// etc
}

Filtering an array result in a for each loop

I have this code to create my array from file:
<?php
$servers = array();
$handle = #fopen("data/data.txt", "r");
if ($handle) {
while (($buffer = fgets($handle)) !== false) {
$line = explode("|", $buffer);
$servers[] = array(
"name" => $line[0],
"ip" => $line[1],
"type" => $line[2],
);
}
fclose($handle);
}
?>
then i have this code to display the array:
<?php
foreach ($servers as $name => $servers): ?>
<td style="width:340px;"> <?php echo $servers['name']; ?></td>
<td style="width:240px;"><?php echo $servers['ip']; ?></td>
</tr>
<?php endforeach; ?>
this is the array sample:
Array(
[0] => Array
(
[name] => aaa
[ip] => 123
[type] => good
)
[1] => Array
(
[name] => bbb
[ip] => 345
[type] => good
)
)
suppose i need to filter the result with array type is good,
im trying with this code but it only returns the last array:
<?php
foreach ($servers as $name => $servers): ?>
<?php if($servers['type']=="good"){?>
<td style="width:340px;"> <?php echo $servers['name']; ?></td>
<td style="width:240px;"><?php echo $servers['ip']; ?></td>
</tr>
<?php } ?>
<?php endforeach; ?>
The error is in the variable name in foreach loop (use $server instead of $serves as $servers already exists and contains your data)
<?php foreach ($servers a $server): ?>
<?php if($server['type']=="good"){?>
<tr>
<td style="width:340px;"> <?php echo $server['name']; ?></td>
<td style="width:240px;"><?php echo $server['ip']; ?></td>
</tr>
<?php } ?>
<?php endforeach; ?>
Edit 1
Filter the array, then print it
<?php
//Filter the array
$goodValues = array_filter($servers, function($e){
return $e['type'] == "good";
//Use this to be sure
//return strtolower($e['type']) == "good";
});
//Print the values
foreach ($goodValues as $value): ?>
<tr>
<td style="width:340px;"> <?php echo $value['name']; ?></td>
<td style="width:240px;"><?php echo $value['ip']; ?></td>
</tr>
<?php endforeach; ?>
As this is just numaric array and you're not using the key anywhere inside the body of the loop, you don't need to use as $key => $value and only as $value will suffice. Also notice the different variable names.
<?php foreach ($servers as $server): ?>
<?php if($server['type']=="good"){?>
<tr>
<td style="width:340px;"> <?php echo $server['name']; ?></td>
<td style="width:240px;"><?php echo $server['ip']; ?></td>
</tr>
<?php } ?>
<?php endforeach; ?>

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>

PHP nesting foreach in table

I can't seem to get my table to have the right output. The code is the following:
<div class="bubbleTitle">Spetsialistide tööaeg graafiku alusel</div>
<table style="width: 600px" class="slicedTable">
<tr>
<th>Spetsialist</th>
<th>Tunnid</th>
</tr>
<tr>
<?php foreach($specs as $specName => $spec): ?>
<td><?php echo $specName?></td>
<?php foreach($tunnid as $tund): ?>
<td><?php echo $tund?></td>
</tr>
<?php endforeach; ?>
<?php endforeach; ?>
I have tried everything in this thread: Nested Loop in table PHP , but none of that has worked either
The output is the following:
name - value
value2
value3
name2 - value
value2
value3
etc.
I would like it to be:
name1 - value1
name 2 - value2 etc.
Where $tunnid comes from:
result = mysql_query("SELECT `worker_id`, SUM(TIMESTAMPDIFF(HOUR, `start`, `end`)) as `total` FROM
`spa_worker_times` WHERE (`start` BETWEEN '".$validated['start']."' AND '".$validated['end']."') AND
(`end` BETWEEN '".$validated['start']."' AND '".$validated['end']."') GROUP BY `worker_id`") or die(mysql_error());
$tunnid = array();
while ($row = mysql_fetch_assoc($result)) {
$tunnid[] = $row['total'];
Where specs come from:
$data = $this->BookingProcedures->query("SELECT AProcedure.name, BookingGroup.booking_package_id > 0 AS pack_proc," .
"SUM(BookingProcedure.price) AS price, Worker.name, COUNT(BookingProcedure.id) AS num" .
" FROM spa_booking_procedure_specialists BookingProcedureSpecialist, " .
"spa_booking_procedures BookingProcedure, " .
"spa_booking_groups BookingGroup, spa_procedures AProcedure, spa_workers Worker" .
" WHERE !BookingProcedure.deleted" .
" AND DATE(BookingProcedure.start) >= '".$validated['start']."'" .
" AND DATE(BookingProcedure.start) <= '".$validated['end']."'" .
" AND BookingProcedureSpecialist.booking_procedure_id = BookingProcedure.id" .
" AND Worker.id = BookingProcedureSpecialist.specialist_id" .
" AND BookingGroup.id = BookingProcedure.group_id" .
" AND AProcedure.id = BookingGroup.procedure_id" .
" GROUP BY AProcedure.name, BookingGroup.booking_package_id > 0, Worker.name");
<div class="bubbleTitle">Spetsialistide tööaeg graafiku alusel</div>
<table style="width: 600px" class="slicedTable">
<tr>
<th>Spetsialist</th>
<th>Tunnid</th>
</tr>
<tr>
<?php foreach($specs as $specName => $spec): ?>
<td><h2><?php echo $specName?></h2>
<table><tr>
<?php foreach($tunnid as $tund): ?>
<td><?php echo $tund?></td>
<?php endforeach; ?>
</tr></table></td>
<?php endforeach; ?>
</tr>
</table>
This will output like this
Name1
value1 | value2 | value3
Name2
value1 | value2 | value3
<?php foreach($specs as $specName => $spec) { ?>
<tr>
<td><?php echo $specName?></td>
<?php foreach($tunnid as $tund) { ?>
<td><?php echo $tund?></td>
<?php } ?>
</tr>
<?php } ?>
will result in
name value value value
name value
name value value
and so on
Where does $tunnid come from. I would assume it contains only values, but in which way, are they in a regular array or an associative? My code would work if $tunnid contains the values to one name. But i assume that is not the case!?
<table style="width: 600px" class="slicedTable">
<tr>
<th>Spetsialist</th>
<th>Tunnid</th>
</tr>
<tr>
<?php foreach($specs as $specName => $spec): ?>
<td><?php echo $specName?></td>
<!-- seperate with anything -->
<td><?php echo implode(',', $tunnid); ?></td>
<?php endforeach; ?>
</tr>
</table>
<?php
$i = 0;
foreach($specs as $specName => $spec){
?>
<tr>
<td><?php echo $specName?></td>
<td><?php echo $tunid[$i++]; ?></td>
</tr>
}
?>

issue with table in php

I'm trying to create a table in php that would show the data on the mysql database based on the check box that is checked by the user.
As you can see in this screen shot, it will have problems when you did not check on a checkbox before the one that will be the last:
http://www.mypicx.com/04282010/1/
Here is my code:
if($_POST['general'] == 'ADDRESS'){
$result2 = mysql_query("SELECT * FROM student WHERE ADDRESS='$saddress'");
?>
<table border='1'>
<tr>
<th>IDNO</th>
<th>YEAR</th>
<th>SECTION</th>
<?php if ( $ShowLastName )
echo "<th>LASTNAME</th>" ?>
<?php if ( $ShowFirstName )
echo "<th>FIRSTNAME</th>" ?>
<?php if ( $ShowMidName )
echo "<th>MIDNAME</th>" ?>
<?php if ( $ShowAddress )
echo "<th>ADDRESS</th>" ?>
<?php if ( $ShowGender )
echo "<th>GENDER</th>" ?>
<?php if ( $ShowReligion )
echo "<th>RELIGION</th>" ?>
<?php if ( $ShowBday )
echo "<th>BIRTHDAY</th>" ?>
<?php if ( $ShowContact )
echo "<th>CONTACT</th>" ?>
</tr>
<?php
while($row = mysql_fetch_array($result2))
{?>
<tr>
<td><?php echo $row['IDNO']?> </td>
<td><?php echo $row['YEAR'] ?> </td>
<td><?php echo $row['SECTION'] ?></td>
<td><?php
if ( $ShowLastName )
echo $row['LASTNAME'] ?></td>
<td><?php
if ( $ShowFirstName )
echo $row['FIRSTNAME'] ?></td>
<td><?php
if ( $ShowMidName )
echo $row['MI'] ?></td>
<td><?php
if ( $ShowAddress )
echo $row['ADDRESS'] ?></td>
<td><?php
if ( $ShowGender )
echo $row['GENDER'] ?></td>
<td><?php
if ( $ShowReligion )
echo $row['RELIGION'] ?></td>
<td><?php
if ( $ShowBday )
echo $row['BIRTHDAY'] ?></td>
<td><?php
if ( $ShowContact )
echo $row['S_CONTACTNUM'] ?></td>
</tr>
<?PHP } ?>
</table>
<?PHP }
mysql_close($con);
?>
What can you recommend so that the output will not look like this when you one of the checkbox before a checkbox is not clicked: http://www.mypicx.com/04282010/2/
instead of
<td><?php
if ( $ShowGender )
echo $row['GENDER'] ?>
</td>
you should do something like
<?php
if ( $ShowGender )
echo "<td>".$row['GENDER']."</td>" ?>
So that the <td> tags only appears if the "if" statement is true.
Ok first thing's first, let's clean your code up, because it's so difficult to read in it's current format:
<?php
if($_POST['general'] == 'ADDRESS'){
$result2 = mysql_query("SELECT * FROM student WHERE ADDRESS='$saddress'");
?>
<table border='1'>
<tr>
<th>IDNO</th>
<th>YEAR</th>
<th>SECTION</th>
<?php if ( $ShowLastName ) { ?><th>LASTNAME</th><?php } ?>
<?php if ( $ShowFirstName ) { ?><th>FIRSTNAME</th><?php } ?>
<?php if ( $ShowMidName ) { ?><th>MIDNAME</th><?php } ?>
<?php if ( $ShowAddress ) { ?><th>ADDRESS</th><?php } ?>
<?php if ( $ShowGender ) { ?><th>GENDER</th><?php } ?>
<?php if ( $ShowReligion ) { ?><th>RELIGION</th><?php } ?>
<?php if ( $ShowBday ) { ?><th>BIRTHDAY</th><?php } ?>
<?php if ( $ShowContact ) { ?><th>CONTACT</th><?php } ?>
</tr>
<?php while($row = mysql_fetch_array($result2)) {?>
<tr>
<td><?php echo $row['IDNO']?> </td>
<td><?php echo $row['YEAR'] ?> </td>
<td><?php echo $row['SECTION'] ?></td>
<?php if ( $ShowLastName ) { echo('<td>'.$row['LASTNAME'].'</td>'); } ?></td>
<?php if ( $ShowFirstName ) { echo('<td>'.$row['FIRSTNAME'].'</td>'); } ?>
<?php if ( $ShowMidName ) { echo('<td>'.$row['MI'].'</td>'); } ?>
<?php if ( $ShowAddress ) { echo('<td>'.$row['ADDRESS'].'</td>'); } ?>
<?php if ( $ShowGender ) { echo('<td>'.$row['GENDER'].'</td>'); } ?>
<?php if ( $ShowReligion ) { echo('<td>'.$row['RELIGION'].'</td>'); }?>
<?php if ( $ShowBday ) { echo('<td>'.$row['BIRTHDAY'].'</td>'); }?>
<?php if ( $ShowContact ) { echo('<td>'.$row['S_CONTACTNUM'].'</td>'); }?>
</tr>
<?php } ?>
</table>
<?php }
mysql_close($con);
?>
Your best bet would be to try putting this code in and telling us if this improves things?
EDIT
Ah, as the others have said your <td> tags are sitting outside of your condition, still, the above code is much easier to read and will help future debugging :-)
You only print table header elements (<th>) if the corresponding $isField variable is set, but you print all table cells, only testing whether or not to print the cell contents.
Instead of all that, loop over the fields to be printed out. No need to test each and every field.
Example form:
<form action="..." method="POST">
<h4>Student Information</h4>
<?php foreach ($studentFields as $key => $label) { ?>
<input type="checkbox" name="show[<?php echo $key; ?>]" id="show_<?php echo $key; ?>"/><label for="show_<?php echo $key; ?>"><?php echo $label; ?></label>
<?php } ?>
<h4>Parent Information</h4>
<?php foreach ($parentFields as $key => $label) { ?>
<input type="checkbox" name="show[<?php echo $key; ?>]" id="show_<?php echo $key; ?>"/><label for="show_<?php echo $key; ?>"><?php echo $label; ?></label>
<?php } ?>
</form>
Form handler:
<table>
<thead><tr>
<?php foreach ($fields as $key => $label) { ?>
<th><?php echo $label; ?></th>
<?php } ?>
</tr></thead>
<tbody>
<?php foreach ($results as $row) { ?>
<tr>
<?php foreach ($fields as $key => $label) { ?>
<td><?php echo $row[$key]; ?></td>
<?php } ?>
</tr>
<?php ?>
</tbody>
The foreach ($results as $row) { needs to be rewritten as a while loop if you stick with the outdated mysql driver, but works with PDOStatement. Switching to PDO also makes it easier to injection vulnerabilities, as prepared statement parameters are invulnerable to them. You can also rewrite that SELECT * to only fetch the requested columns, reducing DB load.
$validFields = array('last' => 'Last Name', 'first' => 'First Name', 'stAddr' => 'Address', ...);
$fields = array_intersect($validFields, $_POST['show']);
You could even make it self-configuring by constructing the $validFields array by inspecting the DB table(s), though this would incur an extra table query.
Yeah, do it the same way as you've done the th tags, with the if statement around the td tags, rather than inside them. Way you've done it now will always show 9 columns, no matter what check boxes are selected.
Your 're printing the cells in the iteration, but only it's content depends on the condition.
<?php
if ( $ShowContact )
echo '<td>' . $row['S_CONTACTNUM'] . '</td>' ?>

Categories