php loop display sum before loop that does calculation - php

Is it possible for me to display the sum at the heading before the program runs through?
while (($data = fgetcsv($handle, 1000, ","))) {
if($data[2] != $prevRow2) {
echo '</div>';
if ($prevRow2 != '') {
$stringData .= '</Payment>';
}
echo "<div id=\"row\">";
echo $sum;
$row++;
$sum = 0;
}
else { echo "<div id=\"filler\"></div>";}
foreach ($data as $key => $d) {
if ($key != 1) {
echo "<div class=\"field\">" .$d . "</div>";
}
}
$sum +=$data[6];
echo "<br/>";
echo "<div id=\"filler\"></div>";
$prevRow2 = $data[2];
}
fclose($handle);
}

You could buffer the output, print out the heading with the sum after the loop ran through, and then output the buffer.
This could be accomplished simply by not echoing but assigning all the values to a variable and echoing that variable at the end - or by using the ob_start, ob_end_flush, etc functions.
So in your example, instead of:
while (true) {
echo "lots of code";
echo "some variable: " . $variable;
$sum = $sum + 1;
}
Write:
while (true) {
$output .= "lots of code";
$output .= "some variable: " . $variable;
$sum = $sum + 1;
}
echo $sum;
echo $output;

Related

PHP Loop on every value on multidimensional array X times [duplicate]

I have a foreach statement in my app that echos a list of my database results:
<?php
foreach($featured_projects as $fp) {
echo '<div class="result">';
echo $fp['project_name'];
echo '</div>';
}
?>
I would like to:
On every third result, give the div a different class. How can I achieve this?
You can use a counter and the modulo/modulus operator as per below:
<?php
// control variable
$counter = 0;
foreach($featured_projects as $fp) {
// reset the variable
$class = '';
// on every third result, set the variable value
if(++$counter % 3 === 0) {
$class = ' third';
}
// your code with the variable that holds the desirable CSS class name
echo '<div class="result' . $class . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
foreach ($featured_projects as $i => $fp) {
echo '<div class="result' . ($i % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
If the $featured_projects array is based on incremental index you could simply use the index and the modulo % operator.
Otherwise you would have to add a counter.
http://php.net/manual/en/language.operators.arithmetic.php
add a counter in this loop and check if counter equals three and apply class.
Using a counter and modulo operator this is easy to implement
<?php
foreach($featured_projects as $fp) {
if(++$i % 3 === 0) {
$class = ' something';
} else {
$class = '';
}
echo '<div class="result' . $class . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
<?php
$i = 0;
foreach($featured_projects as $fp) {
echo '<div class="'.($i++%3 ? 'result' : 'other_class').'">';
echo $fp['project_name'];
echo '</div>';
}
?>
What leaves your code mostly in tact would be
<?php
$i = 1;
foreach($featured_projects as $fp) {
printf ('<div class="%s">',(($i % 3) ? "result" : "result_every_third" ));
echo $fp['project_name'];
echo '</div>';
$i++;
}
?>
But you may want to consider using a for or while construct around "each($featured_projects)" (see http://php.net/manual/en/function.each.php) which may result in neater code.
<?php
$counter = 0;
foreach ($featured_projects as $fp) {
echo '<div class="result' . ($counter++ % 3 === 0 ? ' third' : '') . '">';
echo $fp['project_name'];
echo '</div>';
}
?>
You can add a counter in loop ...try the following...
<?php
$i = 0;
foreach($featured_projects as $fp) {
$i = ++$i;
if(($i%3) == 0)
{
$class1 = 'test1';
}
else
{
$class1 = 'test2';
}
echo '<div class="'.$class1.'">';
echo $fp['project_name'];
echo '</div>';
}
?>
This is the working version, sorry for my prev version:
<?php
$featured_projects[0]['project_name'] = "pippo";
$featured_projects[1]['project_name'] = "pippo2";
$featured_projects[2]['project_name'] = "pippo3";
$class[0] = "class1";
$class[1] = "class2";
$i=0;
foreach($featured_projects as $fp) {
$i++;
if ($i == 3) {
$c = $class[1];
$i=0;
} else {
$c = $class[0];
}
echo "<div class=\"$c\">";
echo $fp['project_name'];
echo "</div>\n";
}
?>
Produces:
<div class="class1">pippo</div>
<div class="class1">pippo2</div>
<div class="class2">pippo3</div>

Moving empty values of an array to the last position

I'm pulling an array from an external API, And I've got some help with usort on here, And It pushes it to the bottom, and empty values are on top. I tried using unset but that just emptied out my entire realArrival values.
e.g.
$fromThis = array(
"realArrival": "",
"realArrival": "Confirm. 06:18",
"realArrival": "Confirm. 06:19"
);
Into:
$intoThis = array(
"realArrival": "Confirm. 06:18",
"realArrival": "Confirm. 06:19",
"realArrival": ""
);
Here is my code on how I tried to do it. I'm sure you are shaking your head at this but here it goes.
$url = 'http://apis.is/flight?language=en&type=arrivals';
$json = file_get_contents($url);
$results = json_decode($json, TRUE);
$results = $results['results'];
function cmp($a, $b) {
return strcmp($a['realArrival'], $b['realArrival']);
}
//Sort Time
usort($results, "compare_time");
function compare_time($a,$b) {
$splitA= count(explode(' ',$a['realArrival']));
$splitB= count(explode(' ',$a['realArrival']));
if($splitA==2 && $splitB==2)
{
$first_time = strtotime(explode(' ',$a['realArrival'])[1]);
$second_time = strtotime(explode(' ',$b['realArrival'])[1]);
if($first_time==$second_time)
{
return strcmp($b['realArrival'], $a['realArrival']);
}
return ($second_time < $first_time) ? 1: 0;
}
return strcmp($a['realArrival'], $b['realArrival']);
}
echo '<table class="highlight bordered responsive-table grey darken-2 col s6">';
echo "<tr>";
echo '<th>Date</th>';
echo '<th>Flight Number</th>';
echo '<th>Airline</th>';
echo '<th>From</th>';
echo '<th>Schedule. Time</th>';
echo '<th>Status</th>';
echo "</tr>";
foreach ($results as $item => $val) {
echo "<tr>";
echo '<td>'.$val['date'].'</td>';
echo '<td>'.$val['flightNumber'].'</td>';
echo '<td>'.$val['airline'].'</td>';
echo '<td>'.$val['from'].'</td>';
echo '<td>'.$val['plannedArrival'].'</td>';
// HERE I TRIED TO TARGET THE EMPTY VALUES
if ($val === "") {
unset($results[$item]);
$results[] = $val;
echo '<td style="font-weight: bold;">'.$val['realArrival'].'</td>';
}
echo '</tr>';
}
I know this might seem clunky, but you could always just do something like...
$items_with_real_arrivals = array();
$items_without_real_arrivals = array();
foreach ($results as $item => $val) {
if ($item[‘realArrival’] === "") { $items_without_real_arrivals.push($item); }
else $items_with_real_arrivals.push($item);
}
$reordered_items = array();
for ($i=0; $i<count($items_with_real_arrivals); $i++) {
$reordered_items.push($item);
}
for ($i=0; $i<count($items_without_real_arrivals); $i++) {
$reordered_items.push($item);
}
foreach ($reordered_items as $item => $val) {
echo "<tr>";
echo ' <td>'.$val['date'].'</td>';
echo ' <td>'.$val['flightNumber'].'</td>';
echo ' <td>'.$val['airline'].'</td>';
echo ' <td>'.$val['from'].'</td>';
echo ' <td>'.$val['plannedArrival'].'</td>';
echo ' <td style="font-weight:bold;">' . $val['realArrival'].'</td>';
echo '</tr>';
}

Using DOM to get dynamic table data but not following tables sort

I've got a table that is default sorted ascendingly by its 2nd column by numeric value.
I'm trying to grab the top 5 rows from this table, but my script doesn't seem to want to follow the tablesorter forced sort order I have, it's just taking the default non sorted data.
So how do I get my script to grab the sorted table data? I don't want to have to grab all the data and sort it again for this script.
here is my code
<?php
include("bestbrokers_array.php");
require('simple_html_dom.php');
$table = array();
$html = file_get_html('http://www.forexfbi.com/best-forex-brokers-comparison/');
$num=1;
foreach($html->find('tr') as $row) {
if($num <= 6)
{
$rating = $row->find('td',1)->innertext;
$name = $row->find('td',0)->plaintext;
$table[$name][$rating] = true;
$num++;
}
}
html_show_array($table);
?>
and..
<?php
function do_offset($level){
$offset = ""; // offset for subarry
for ($i=1; $i<$level;$i++){
$offset = $offset . "<td></td>";
}
return $offset;
}
function show_array($array, $level, $sub){
if (is_array($array) == 1){ // check if input is an array
foreach($array as $key_val => $value) {
$offset = "";
if (is_array($value) == 1){ // array is multidimensional
echo "<tr>";
$offset = do_offset($level);
echo $offset . "<td>" . $key_val . "</td>";
show_array($value, $level+1, 1);
}
else{ // (sub)array is not multidim
if ($sub != 1){ // first entry for subarray
echo "<tr nosub>";
$offset = do_offset($level);
}
$sub = 0;
echo $offset . "<td main ".$sub." width=\"120\">" . $key_val .
"</td>";
echo "</tr>\n";
}
} //foreach $array
}
else{ // argument $array is not an array
return;
}
}
function html_show_array($array){
echo "<table cellspacing=\"0\" border=\"2\">\n";
show_array($array, 1, 0);
echo "</table>\n";
}
?>

php mysql_fetch_array every 25 items wrap a div

I want to mysql_fetch_array 100 items from mysql database. then every 25 items wrap a div.
also, I make a total items result check.
My code as below, but it will add <div> to every item, no as my require. So how to make it easier? Thanks.
if (mysql_num_rows($result) != 0) {
$total = mysql_num_rows($result);
$num = 1;
while ($row = mysql_fetch_array($result)) {
if ($num === 1) {
echo '<div>';
}
echo $row['title'] . '<br />';
if ($total < 26) {
echo '</div>';
}
else {
if ($num === 26) {
echo '<div>';
}
if ($total < 51) {
echo '</div>';
}
else {
if ($num === 51) {
echo '<div>';
}
if ($total < 76) {
echo '</div>';
}
else {
if ($num === 75) {
echo '<div>';
}
if ($total < 101) {
echo '</div>';
}
}
}
}
$num++;
}
}
You can use the mod operator.
See: http://php.net/manual/en/internals2.opcodes.mod.php
echo '<div>';
while($row = mysql_fetch_array($result)){
....
if (($num % 25) === 1) { echo '</div><div>' }
$num++;
}
echo '</div>';
Try This...
if(mysql_num_rows($result)!=0){
$total = mysql_num_rows($result);
$num=1;
while($row = mysql_fetch_array($result)){
if($num===1)
echo '<div>';
echo $row['title'].'<br />';
if($num==25){
echo '</div>';
$num=1;
}
$num++;
}
}
use the mod operator.
$num =1;
while($row = mysql_fetch_array($result)){
if (($num % 25) === 1) { echo '<div>' }
-------here data ----
if (($num % 25) === 0) { echo '</div>' }
$num++;
}
My advice is to separate your concerns... Give it a shot more like this:
// first get all your data.
$results = array();
while($row = mysql_fetch_array($result)){
$results[] = $row;
}
// now you have an array of all of your records.
if (!empty($results)) {
// total count of the array up front.
$total = count($results);
$interval = 0;
// save the data in a buffer for echoing later.
$buffer = array('<div>');
foreach($results as $row) {
$buffer[] = $row['title'] . '<br />';
if (++$interval === 24) { // notice the prefix ++
$interval = 0;
// close and re-open divs
$buffer[] = '</div><div>';
}
}
// one final close tag
$buffer[] = '</div>';
// now we zip it up and echo the content.
echo implode('', $buffer);
}
Here is how I do it...
$count = 0;
while($row = mysql_fetch_array($result)){
if ($count%$25 == 0)
{
echo "<div>";
}
//whatever your data goes here
count++
if ($count%$25 == 0)
{
echo "</div>";
}
}

loop not functioning properly

I am unable to get this loop to function properly. Whenever ($records[$row][2] == $prevRow2) I need it to recreate the class=field and only close the div=row that's part of the group where ($records[$row][2] == $prevRow2). Please help!!
if (($handle = fopen('upload/ATLANTA.csv', "r")) !== FALSE) {
$prevRow2 = false;
$row=0;
while (($data = fgetcsv($handle, 1000, ","))) {
$num = count($data);
$records[] = $data;
echo "<div id=\"row\"><div id=\"num\">" .$row. "</div>";
echo 'Is '. $prevRow2 . 'the same as ' .$records[$row][2];
if ($records[$row][2] == $prevRow2) {
for ($c=0; $c < $num; $c++) {
if ($c != 1) {
echo "<div class=\"field\">" . $data[$c] . "</div>";
}
}
$prevRow2 = $records[$row][2];
$row++;
echo "<div id=\"filler\"></div>";
}//if close
else {
for ($c=0; $c < $num; $c++) {
if ($c != 1) {
echo "<div class=\"field\">" . $data[$c] . "</div>";
}
}
$prevRow2 = $records[$row][2];
$row++;
}//close else
echo '</div>';
}//close while
fclose($handle);
}
$row seems to be null until the line you make $row++;
Some output and/or further description of your data would really help, but I notice a few things.
1 - Your closing if and else do exactly the same thing except for this filler div. I get the impression this is not what you desire, but I don't really understand enough to suggest what to do.
for ($c=0; $c < $num; $c++) {
if ($c != 1) {
echo "<div class=\"field\">" . $data[$c] . "</div>";
}
}
$prevRow2 = $records[$row][2];
$row++;
This code is common to both the if and else blocks, so it executes no matter what. Is that what you want? If so, you might as well move it out of the if and move only the filler div into the if, nothing in the else.
2 - What is the purpose of $records and $records[$row]. As far as I can see, $records[$row] === $data whenever its used.
3 - The div with id=row is closed at the end of every while loop. You seem to suggest you don't want this, put if you only do it when $records[$row][2] AKA $data[2] matches the previous iteration's, I don't think your HTML will be well formed.
4 - try using foreach instead of your foor loops
It looks like Company is actually index 3, not 2.
$prevData3 = false;
$row=0;
while (($data = fgetcsv($handle, 1000, ","))) {
if ($data[2] != $prevData2)
{
if ($prevData2) echo '</div>';
echo "<div id=\"row\"><div id=\"num\">" .$row. "</div>";
row++;
}
else echo "<div id=\"filler\"></div>";
foreach ($data as $d) {
if ($c != 1) {
echo "<div class=\"field\">" . $d . "</div>";
}
}
echo "<br />";
$prevData2 = $data[2];
}
echo CLOSE_DIV;

Categories