I'm trying to set up my php script to add to a value to the previous value that is returned in the loop. Below is an example. The number on the left is the number that comes from the loop and is returned as $axle. The number on the right is the total as is the number from above added to the number on the right '$totalAxle'. I tried a few examples that I found online but they did not seem to work for me. My latest attempt which is the code below resulted in an error Notice: Array to string conversion
6/6
6/12
4/16
echo "<td>";
$axle = "Not Found!";
foreach ($railunit->railUnit as $ru) {
if((string)$ru->rvXMLfilename == $rvXMLfilename){
$axle = (string)$ru->axleCount;
$array = array("axle" => $axle);
$axleTotal = array();
$i = 1;
$previous = 0;
foreach($array as $key => $val) {
$axleTotal['number'.$i] = $val+$previous;
$previous += $val;
$i++;
};
}
}
echo $axle, "/", $axleTotal;
echo "</td>";
Turns out that your foreach could be way simpler. I was able to solve it together with OP after a discussion in chat.
// add $total = 0; OUTSIDE of any loops so it doesnt get overwritten
$total = 0;
foreach($railunit->railUnit as $ru) {
$axle = $ru->axleCount;
$total = $total + $axle;
}
echo $axle . "/" . $total;
Related
I have the following script that divides the total by the number of people and stores the results in an array.
Instead of dumping the $result array at the end, I wonder if I could echo out the value of each array item in the for loop as it goes?
// initial conditions
$total = 1001;
$people = 5;
// count what is the minimal value, that all the results will have
$value = floor($total / $people);
$result = array_fill(0, $people, $value);
// distribute missing "+1"s as needed in the result
$overheads = $total - $value * $people;
for ($i = 0; $i < $overheads; $i++) {
$result[$i]++;
}
// voila...
var_dump($result);
So, the above script should loop out:
200
200
200
200
201
Technically speaking, you can't "echo out the value of each array item
in the for loop as it goes" because you're not filling the arrays
in a loop, you're filling with array_fill(). The loop you have is to
work with the remainder. If you echo out there, you'll get partial
results. So either you keep your code and echo the values at the end,
with a simple line:
foreach ($result as $r) echo "$r\n";
Or you modify your code to fill the arrays in another manner. Which
might be interesting. Note that you're forgetting about the modulus
operator, %, for the remainder of division. This line:
$overheads = $total - $value * $people;
Could be written simply as:
$overheads = $total % $people;
An idea to fill in a loop:
// initial conditions
$total = 1001;
$people = 5;
$value = floor($total/$people);
$overheads = $total % $people;
foreach (range(1, $people) as $p) {
$r = $value;
if ($overheads) {
# if there is still remainders:
$r++;
$overheads--;
}
# echo the value and also store it
echo "$r\n";
$result[] = $r;
}
// initial conditions
$total = 1001;
$people = 5;
// count what is the minimal value, that all the results will have
$value = floor($total / $people);
$result = array_fill(0, $people, $value);
// distribute missing "+1"s as needed in the result
$overheads = $total - $value * $people;
$i = 1;
foreach($result as $res)
{
if ($i < $people){
echo $res . "\n";
}else{
echo $res + 1 . "\n";
}
$i++;
}
// voila...
I made a loop then sum it into variable $jumlahtotal, what I confuse is the value in $jumlahtotal is true when I try to echo it, but I getting undefined variable error on this $jumlahtotal
Note : i tried declare it outside the foreach but still getting error undefined variable;
here's my code :
$total = 0;
$totalberat = 0;
if (isset($_SESSION['items'])) {
foreach ($_SESSION['items'] as $key => $val) {
$query = mysqli_query($koneksi, "select * from barang where br_id = '$key'");
$data = mysqli_fetch_array($query);
$jumlah_harga = $data['br_hrg']*$val;
$total += $jumlah_harga;
$berat = $data['brt_brg']*$val;
$totalberat += $berat;
$jumlahtotal += $val;
}}
?>
Some tips:
Start declaring $jumlahtotal=0 above $totalberat.
$total = 0;
$totalberat = 0;
$jumlahtotal = 0;
Validate the value of $val before adding its value to $jumlahtotal.
if (is_int($val)) {
$jumlahtotal += $val;
} else {
die('$val not int');
}
If its all okay, debug the code and check the code is reaching the '$jumlahtotal += $val;' sentence and debug it.
$jumlahtotal += $val;
var_dump($jumlahtotal);
It should help you to find the issue.
I'm trying to find a way to extract an average of a subkey of several arrays (up to 80) UNTIL another subkey has a certain value.
The full code contains the following:
$element = $html->find('table',3);
$i = 0;
foreach($element->find('tr') as $row){
if($i >= 2){
$racelapno = $row->find('td',0)->plaintext;
$racelaptime = $row->find('td',1)->plaintext;
$raceposition = $row->find('td',2)->plaintext;
$racetyre = $row->find('td',3)->plaintext;
$raceweather = $row->find('td',4)->plaintext;
$racetemp = $row->find('td',5)->plaintext;
$racehum = $row->find('td',6)->plaintext;
$raceevent = $row->find('td',7)->plaintext;
$racelap[$i] = Array();
$racelap[$i][0] = $racelapno;
$racelap[$i][1] = $racelaptime;
$racelap[$i][2] = $raceposition;
$racelap[$i][3] = $racetyre;
$racelap[$i][4] = $raceweather;
$racelap[$i][5] = $racetemp;
$racelap[$i][6] = $racehum;
$racelap[$i][7] = $raceevent;
}
$i+=1;
}
So I want to find the average of all $racetemp in the different arrays until an array returns "pit" on $raceevent.
Browsing on here I have found a way to find the average of all arrays which looks as followed:
$counter = 0;
$total = 0;
foreach($racelap as $row) {
$counter++;
$total += $row['5'];
}
$avgracetemp = $total / $counter;
But now I need to add some sort of stop when $racelap[$i][7] contains "pit", but also continue again until it contains "pit" again.
Hope anyone can help me, it is appreciated :)
If I understand you correctly, in foreach you can just use something like:
if (strpos($row['7'], 'pit') !== false) {
$counter++;
$total += $row['5'];
}
I have a while loop that contains another while loop. Both loops are iterating over different mysql result sets. The problem is that the second time the outer while loop calls the inner while loop it doesn't run. Does Mysql_fetch_row discard itself after it has been iterated over?
Here is what the code looks like:
$counter = 0;
while ($r = mysql_fetch_row($result)){
$col = "";
$val = "";
while($d = mysql_fetch_row($dictionary)){
$key = $d[0];
for($i= 0; $i< count($tableColumNames); $i++){
if($tableColumNames[$i] == $key){
$col .= "`".$d[1]."` ,";
$val .= "`".$r[$i]."` ,";
/* echo $tableColumNames[$i]." table ColumnName <br>";
echo $d[1]." key<br>"; */
}
}
echo $key."round".$counter."<br>";
}
var_dump ($col);
var_dump ($val);
$counter++;
echo $counter;
}
And here is what the output is like: You can see that the $result holds four records and the output is showing that the loop is working correctly. However, the inner loop over the $dictionary result set doesn't run the second time $result is being iterated over. Any ideas why? I tried to use mysql_fetch_array as well but still the same result.
Thanks
When ever you are calling mysql_fetch_row($dictionary) It gives you a particular column details in the row and it deletes it from the $dictionary array.
So there are no elements for next use.
Instead of declaring $dictionary outside declare it in while loop. It will solve your problem.
$counter = 0;
while ($r = mysql_fetch_row($result)){
$col = "";
$val = "";
$dictionary=("Select * from database");//your own logic
while($d = mysql_fetch_row($dictionary)){
$key = $d[0];
for($i= 0; $i< count($tableColumNames); $i++){
if($tableColumNames[$i] == $key){
$col .= "`".$d[1]."` ,";
$val .= "`".$r[$i]."` ,";
/* echo $tableColumNames[$i]." table ColumnName <br>";
echo $d[1]." key<br>"; */
}
}
echo $key."round".$counter."<br>";
}
var_dump ($col);
var_dump ($val);
$counter++;
echo $counter;
}
or you can use mysql_data_seek().
I've encountered something that seems like a strange performance problem. Running this code:
<?php
function test_ref(&$test)
{
for ($i = 0; $i < 100000; $i++)
{
$foo = "s" . rand(1, 1000);
if (!array_key_exists($foo, $test))
{
$test[$foo] = array();
}
$test[$foo][] = rand(1, 10);
}
}
function test()
{
$test = array();
for ($i = 0; $i < 100000; $i++)
{
$foo = "s" . rand(1, 1000);
if (!array_key_exists($foo, $test))
{
$test[$foo] = array();
}
$test[$foo][] = rand(1, 10);
}
return $test;
}
$scriptstart = microtime(true);
$test = array();
test_ref($test);
$sum = 0;
foreach ($test as $key => $val)
{
foreach ($val as $val2)
{
$sum += $val2;
}
}
echo "sum " . $sum . "<br>";
$scriptelapsed = microtime(true) - $scriptstart;
echo "time taken " . $scriptelapsed . "<br>";
$scriptstart = microtime(true);
$test = test();
$sum = 0;
foreach ($test as $key => $val)
{
foreach ($val as $val2)
{
$sum += $val2;
}
}
echo "sum " . $sum . "<br>";
$scriptelapsed = microtime(true) - $scriptstart;
echo "time taken " . $scriptelapsed . "<br>";
?>
I get these results:
sum 548521
time taken 12.37544798851
sum 551236
time taken 0.29530310630798
What's going on here? It seems to be connected to the fact that I insert sub-arrays into the array, though I don't see why passing by reference should be that much slower.
(this is on PHP Version 5.3.3-7+squeeze14 with Suhosin Patch 0.9.9.1)
(edit: fixed using of unset variables, still the same result)
You're accessing values from another scope - that's always slower than only using ones that are defined within the function itself. Here's a nice blog post explaining it, even though that's not its primary topic: PHP internals: When does foreach copy?
It is just my guess but I think we could explain it like this:
when using no reference a local variable is created (that is directly pointing to a memory) and the loop goes like:
$i = 0; $foo = 499; $test[499] = array(); $test[499][] = 2; "commit" directly to a memory
finaly, the value $test is then returned - reading directly from the memory pointer
when using referenced value, the variable passed is like a pointer to a pointer (that is finally pointing to a memory)
in this case the loop looks like:
$i = 0; $foo = 354; $test[354] = array(); $test[354][] = 7; "commit" to a memory via pointer to a memory pointer
I guess therefore there is at least one more step neccessary when working with referenced variables...