multiply 2 values from different table using codeigniter and postgresql foreach() - php

Here's the code from my
Controller Page
public function table1(){
$this->load->model('test_model');
$data['value']= $this->test_model->getAlltable1();
$data['value2']= $this->test_model->getAlltable0();
$this->load->view('table1', $data);
}
Views Page
<table class="table">
<tbody>
<?php foreach ($value as $v){ ?>
<?php foreach ($value2 as $v2){ ?> //different table
<tr>
<td><?php echo $v->tech_voc?></td>
<td><?php echo ($v->tech_voc*$v2->tech_voc)?></td>
</tr>
<?php } ?>
<?php } ?>
The output is somewhat like this
1 .75
1 .75
1 .75
1 .75
What I want to display is something like this
1 .75
What happen here is that, instead it multiply once, it all multiply each row. And I think it is because I put foreach inside a foreach Please help me.
EDIT
Oh yeah, I already tried deleting the foreach value2
but it says v2 is undefined variable
HOPE it helps.
NEW EDIT:---------------------------------------

If you're trying to multiply where the keys are the same ($value[0]*$value2[0], $value[1]*$value2[1], etc) try this.
<?php
$col1_sum = 0;
$col2_sum = 0;
foreach ($value as $k => $v){ ?>
<tr>
<td><?php echo $v->tech_voc?></td>
<td><?php echo ($v->tech_voc*$value2[$k]->tech_voc)?></td>
<?php //update sums
$col1_sum += $v->tech_voc;
$col2_sum += ($v->tech_voc*$value2[$k]->tech_voc);
?>
</tr>
<?php } ?>
<!-- row with sums -->
<tr>
<td><?php echo $col1_sum?></td>
<td><?php echo $col2_sum?></td>
</tr>
Edited based on comments/chat to include a sum row.

Related

Foreach loop Json array

I am learning to work with Json at the moment, I have figured out how to display data for Name and Craft in space in the moment.
I cannot figure out how to display number of people.
Is not correct, I am receiving error
foreach ($json_data['number'] as $key => $value) {
echo $value;
}
Also does not work
foreach($json_data as $key=>$value)
{
echo $key['number'];
}
// Read JSON file
$json = file_get_contents('http://api.open-notify.org/astros.json');
//Decode JSON
$json_data = json_decode($json,true);
HTML
<table>
<tr>
<th>Name</th>
<th>Craft</th>
</tr>
<?php foreach($json_data['people'] as $key=>$value): ?>
<tr>
<td><?php echo $value['name']; ?></td>
<td><?php echo $value['craft']; ?></td>
</tr>
<?php endforeach; ?>
</table>
I want to display number of people in the space by using foreach loop
Change your code to
<?php
// Read JSON file
$json = file_get_contents('http://api.open-notify.org/astros.json');
//Decode JSON
$json_data = json_decode($json,true);
$peopleCount = 0;
?>
<table>
<tr>
<th>Name</th>
<th>Craft</th>
</tr>
<?php foreach($json_data['people'] as $key=>$value):
$peopleCount++;
?>
<tr>
<td><?php echo $value['name']; ?></td>
<td><?php echo $value['craft']; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php
echo "Total People count: ". $peopleCount;
explanation:
$peopleCount variable is holding the number of people.
At first, its values is 0.
When iterating over the array the $peopleCount's value is incrementing by 1 ($peopleCount++; is equal to $peopleCount = $peopleCount +1;)
PS:
Your code had missing PHP closing tag at line number 8. I fixed it.
foreach is used to loop through an array. In your JSON output number is not returned as an array, so you do not need to use foreach loop for displaying number. You can just display the Number using following code:
<?php echo $json_data['number']; ?>

Difficult with foreach, sum and table (noob)

I have a table that is created by my billing manager. It has a foreach that inserts the calls in the table that list it, pretty simple.
I have as a task from my boss to include on the bottom of the table the sum of all call durations, which is an item from it, but doesn't appear as a sum.
After some hours, I surrendered to my ignorance. I guess the easiest way should be to put on this (resumed) section to include the value on an array:
foreach ($this->call_list as $id => $callsList): ?>
<td class="text-center"><?php echo $this->format->fmt_segundos(array("a" => $callsList['billsec'], "b" => 'hms')); ?></td>
<?php endforeach?>
And then, down here, I would put the code to sum all the values on that variable:
<td class="text-center"><?php echo $this->translate("Duration") ?> <?php echo "<br>"; ?> <label class="label label-info"><?php echo $this->totals['tempo']; ?></label></td>
But I don't know how. Could you guys help me?
I don't know spanish but i assume that function, fmt_segundos returns duration in seconds. In this case, the following code should do the trick:
<table>
<thead>
<td>id</td><td>Duration</td>
</thead>
<?php
$TOTAL= 0;
foreach ($this->call_list as $id => $callsList){
$a = $this->format->fmt_segundos(array("a" => $callsList['billsec'], "b" => 'hms'));
$TOTAL += $a;
echo '<tr>';
echo '<td class="text-center">'.$id.'</td>';
echo '<td class="text-center">';
echo gmdate("H:i:s", $a);
echo '</td>';
echo '</tr>';
}
?>
<tfoot>
<td>TOTAL</td><td><?=gmdate("H:i:s",$TOTAL)?></td>
</tfoot>
</table>

Mysql returns duplicate in html table

I am trying to populate html table with data from mysql.But i am stuck on this part where each time i add some data it keeps repeating. On the picture below you can see that Test 1 repeat each time for every P20,P21,P24,P22,P23 and i needed to be one TEST1 for all of them. When i add Test 2 with value 19000 its making new P20 and all data come from Test 1 to Test 2. Can someone help me how to fix this.Any hint or suggestion wil be appreciated. Thank you all very much (Sorry for my bad english)
This is code that runs this
$sql = 'SELECT DISTINCT Pers.naam, Rol.funkcija,pdata.broj
FROM ids
left JOIN Pers ON ids.persid = Pers.id
left JOIN Rol ON ids.rolid = Rol.id
left JOIN pdata ON ids.pdataid = pdata.id
';
$query = $conn->prepare($sql);
$query->execute();
$testing = $query->fetchAll(PDO::FETCH_ASSOC);
?>
<table>
<tr>
<th>P Small <small>(NONE)</small></th>
<?php
foreach ($testing as $test):
?>
<th>
<?php
echo $test['naam'] . '<br />';
?>
</th>
<?php
endforeach;
?>
</tr>
<tr>
<th>TESTING LINES</th>
</tr>
<?php foreach ($testing as $test): ?>
<tr>
<td><?php echo $test['funkcija']; ?></td>
<?php endforeach; ?>
<?php
foreach ($testing as $test):
?>
<td><?php echo $test['broj']; ?></td>
<?php
endforeach;
?>
</tr>
</table>
I would like to have it like this
There is some refactoring required to get to the output you want.
You seem to be enumerating quite a lot of data from your SQL result, so there is some grouping required to make things easier.
To get the appropriate number to each "naam" and "funkcija" you can use array_filter which however could theoretically return several numbers in each case.
You'll also have to nest a couple foreach instead of running them after one another.
If I understand your data structure correctly, this should at least give you a good starting point for the output you want:
<?php
// ...
$testing = $query->fetchAll(PDO::FETCH_ASSOC);
$naams = array_unique(array_column($testing, "naam"));
$funkcijas = array_unique(array_column($testing, "funkcija"));
?>
<table>
<tr>
<th>P Small <small>(NONE)</small></th>
<?php foreach ($naams as $naam): ?>
<th>
<?php echo $naam; ?>
</th>
<?php endforeach; ?>
</tr>
<tr>
<th>TESTING LINES</th>
</tr>
<?php foreach ($funkcijas as $funkcija): ?>
<tr>
<td><?php echo $funkcija; ?></td>
<?php foreach ($naams as $naam): ?>
<?php
$data = array_filter(
$testing,
function ($v) use ($naam, $funkcija)
{
return $v["naam"] === $naam && $v["funkcija"] === $funkcija;
}
);
foreach ($data as $value): ?>
<td><?php echo $value["broj"]; ?></td>
<?php endforeach; ?>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</table>

For loop inside Foreach

I got a foreach which loops through my database for each user.
<?php
foreach($users as $user) {
?>
<tr>
<td>
<?php
for ($i=1; $i < 52; $i++) {
echo $i;
}
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
This loop through database and echos the username, now I tried to build a for loop inside this so that every user has a number, I took as an example a very basic for loop ( it will be changed later).
The problem is that I get all numbers printed out for each user, but I just want to print out the number once for a user. How do I solve this.
If you want unique index number for user, you do not need extra loop.
Just add an increment variable:
And increment it in existing loop.
<?php
$i=0;
foreach($users as $user) {
++$i; // For printing first user, it will be 1 not 0.
// Therefore, increment is placed before printing name.
?>
<tr>
<td><?php echo $i;?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php
}
?>
This should be enough to achieve what you're trying to do :
Your for() isn't needed since foreach() already create a loop, you just have to use this loop to increment a value (here called $i) then display it.
Also you should avoid to open your php tags ten thousands times for a better visibility into your code :)
<?php
$i = 0;
foreach($users as $user) {
$i++;
echo'<tr>
<td>'.$i.'</td>
<td>'.$user['firstname'].'</td>
</tr>';
?>
<?php
$i=1;
foreach($users as $user) {
?>
<tr>
<td>
<?php
echo $i++;
?>
</td>
<td>
<?php echo $user['firstname']; ?>
</td>
</tr>
<?php
}
?>
Try to use the key in foreach
<?php foreach ($users as $key => $user) : ?>
<tr>
<td><?php echo $key; ?></td>
<td><?php echo $user['firstname']; ?></td>
</tr>
<?php endforeach; ?>

How to sum up values inside a array variable?

I have retrieved some values from database. In my view file I have the following:
$row['fee_amount'];
Now, I want to sum up all the values inside $row['fee_amount']; and then show it.
I know I could sum up when querying the database, but I am interested to learn how to add using PHP .
Would you please kindly teach me how to do it?
EDIT
<?php if(count($records) > 0) { ?>
<table id="table1" class="gtable sortable">
<thead>
<tr>
<th>S.N</th>
<th>Fee Type</th>
<th>Fee Amount</th>
</tr>
</thead>
<tbody>
<?php $i = 0; foreach ($records as $row){ $i++; ?>
<tr>
<td><?php echo $i; ?>.</td>
<td><?php echo $row['fee_type'];?></td>
<td><?php echo $row['fee_amount'];?></td>
</tr>
<?php } ?>
</tbody>
<tr>
<td></td>
<td>Total</td>
<td>
I WANT TO DISPLAY THE SUMMATION RESULT HERE ADDING UP VALUES INSIDE THIS>>> <? $row['fee_amount']; ?>
</td>
</tr>
</table>
<?php } ?>
In your view file, with your foreach loop, add a $sum variable next to your $i counter and add the amount per each iteration (similar to like you increase $i):
<?php
$i = 0;
$sum = 0;
foreach ($records as $row)
{
$i++;
$sum += $row['fee_amount']; ?>
(I put this over multiple lines to make it more readable).
After the foreach has finished, $sum contains the total amount:
<td>Total: <?php echo $sum; ?></td>
That simple it is. You only need a new variable ($sum) and do the calculation.
Use a loop
$sum = 0;
while($row...){
$sum += $row['fee_amount']
}
echo $sum;
You could use;
$someValue = 0;
foreach($row["fee_amount"] as $value) {
$someValue = $someValue + $value;
}
using this php function, if $row['fee_amount'] is an array ^_^
for example:
$a = array(2, 4, 6, 8);
array_sum($a)

Categories