Since i have many diffrent workers on my workkey and i just want to print every work once. I Though of doin a check like this.
At the end of the loop i wanna save the value from workkey. So before every print i will check, If the new workkey is diffrent from the last one = Dont print.
$counter = 0;
while(db2_fetch_row($queryexe)) {
$work = db2_result($queryexe, 'workkey');
$fname = db2_result($queryexe, 'fname');
$lname = db2_result($queryexe, 'lname');
if ($workkey != $saveworkkey){
$counter = 0;
}
if ($counter < 1){
print ( some stuff)
print ( some stuff)
print ( some stuff)
}
$workkey = $saveworkkey;
$counter++;
}
What I do to solve the issue is to add all values to an array with the key as array key. This way, even if there are duplicates they will overwrite eachother.
$workers = array()
while ($record = db2_fetch_row($queryexe)) {
$workers[$record['workkey']] = $record;
}
To print your values you can simply foreach
foreach ($workers as $worker) {
// print worker
}
Related
i have data from php loop foreach like this
foreach ($query->result() as $row) {
echo $row->name;
}
how to make the result show only the end data without remove others if data has same (if data have same value, hide all except the last one) like this:
*sorry bad english, this is the first time i ask here. thank you
Online Check, This is just a demo example.
See below the real example:
At first you need to use array_search for get the position of the same data, if exist then just remove it using $arr[$pos] = '';, and each and every time you need to import data into the new array called $arr and after completing fetching data you need to use a foreach loop to print them.
$arr = array();
foreach($query->result() as $row){
$pos = array_search($row->name, $arr);
if($pos !== false)
$arr[$pos] = '';
$arr[] = $row->name;
}
foreach($arr as $val){
echo $val.'<br/>';
}
Check this and let me know.
The data_seek method might help. This assumes your array is reasonable ordered to begin with.
$rowCount = 0;
$res = $query->result();
foreach($res as $row) {
if ($rowCount < $res->num_rows - 1) {
// set internal pointer to next row
$res->data_seek($rowCount + 1);
// if the row names match, print an empty string
// otherwise print the current name
$nextRow = $res->fetch_row();
if ($row->name == $nextRow->name) {
echo "";
// reset the internal pointer
$res->data_seek($rowCount);
} else {
echo $row->name;
}
} else {
echo $row->name;
}
// update the row count
$rowCount += 1;
}
I am trying to build a loop to show different location names based on the page ID. I am trying a for loop, but not sure how to get the 2 results, I tried a foreach, but still got lost.
$location = array( "Frisco" => "1507", "McKinney" => "1509");
$count = count($location);
for($i = 0; $i < $count; $i++){
if(is_page($location[$i])) {
$location = "";
}
}
Need results =
// Add Shortcode
function dynamicLocation(){
if(is_page('1')){
$location = "McKinney";
}
else if(is_page()){
$location....
}
}
Forget for, use foreach:
foreach ($location as $key=>$value){
//here $key is the location and $value is the ID
//e.g. $key="Frisco", $value="1507"
}
I have foreach cycle in PHP. It is going trough json items, and for every item I have value that changes. I set my cycle to run every 20min.
I need my value to be saved and next time foreach runs for that item I need to assign at the beginning old value to variable so I can compare old and new value in foreach cycle.
here is the code:
// Parse results and extract data to display
foreach($json as $quote)
{
//add before value
$state1 = $state2;
// assign object elements to vars
$q_change = $quote->c;
$q_price = $quote->l;
$q_name = $quote->t;
$q_changep = $quote->cp;
$q_symbol = $quote->t;
$q_ltrade = $quote->lt;
$q_exch = $quote->e;
$state2 = $q_change;
$parametar = $q_change - $state1;
// Define class based on change
if ( $parametar < -0.3 ) { $chclass = "minus"; }
else if ( $parametar > 0.3 ) { $chclass = "plus"; }
else if ( $q_change < 0 ) { $chclass = "minus"; }
else if ( $q_change > 0 ) { $chclass = "plus"; }
else { $chclass = "zero"; $q_change = "0.00"; }
}
Any idea how that might work?
You will have to save the JSON on the file system to retrieve the values on subsequent runs:
$oldJsonFile = '/path/to/data.json';
if (is_file($file)) {
$oldJson = file_get_contents($oldJsonFile);
}
// Do the work, and then store it back to the file system
file_put_contents($cacheFile, $newJson);
I'd imagine you are looking to do something like the following. Sessions will store your data for the next foreach execution.
session_start();
$previousData = $_SESSION['PreviousData'];
foreach($array as $key => $value){
//... all your foreach calculations
//end of foreach
}
$_SESSION['PreviousData'] = $thisData;
Alternatively you could store the data into a database, that's what they are for. Then you'll be free to do all kinds of interesting queries on past records etc.
When I ouput these txt files, I am trying to group them by unique county with a count limitation per county file. For example, let's say the query returns 2 unique counties in this accessable result field: $row['county_txt'].. Let's say I set the $per_file limitation to 2500. I have the script working now with the per_file etc but not with the counties grouping. Below is somewhat of a mash of where I am at. Thanks for any guidance in helping me resolve this.
Output examples:
Green County - Total Green county results 2900 output would be 2 files.
Output files would be:
Green-#1-20130627-2500.txt
Green-#2-20130627-400.txt
Red County - Total Red county results 12650 output would be 5 files.
Output files would be:
Red-#1-20130627-2500.txt
Red-#2-20130627-2500.txt
Red-#3-20130627-2500.txt
Red-#4-20130627-2500.txt
Red-#5-20130627-150.txt
... // earlier part of script
// Functions I've been attempting
$county[] = $row['county_txt'];
function unique_county() {
foreach($county as $unq_cnty) {
echo $unq_cnty;
return $unq_cnty;
}
}
function get_unique_county() {
$column = array();
while($row = mysql_fetch_array($result)){
$column[] = array_unique($row['county_txt']);
echo $column;
}
}
get_unique_county();
$file_count = 1;
$recs = 0;
$per_file = 2500;
$footer = "FOOTER";
$default_contents = $contents = array("BODY CONTENT TOP");
while ($row = mysql_fetch_array($result)) {
$line = "...";
$contents[] = $line; // Each array element will be a line in the text file
$i++;
$recs++;
if ($county == $unq_cnty && $i == $per_file) {
$contents[] = $footer; // Add the footer to the end
file_put_contents($unq_county . "-#" . $file_count . "-" . date('Y') . "-" . $recs . '.txt', implode("\r\n", $contents));
$i = 0;
$recs = 0;
$contents = $default_contents;
$file_count++;
} // End of if()
} // End of while()
You need a counter, and then be able to reset it (upon resetting it, you save the file).
Example (untested, example only):
<?php
$rowCounter = 0;
$fileCounter = 1;
$startID = md5(microtime(1));
$fp = fopen("{$startID}.txt", "w");
while ($row = mysql_fetch_array($result)) {
$rowCounter++;
fwrite($fp, $row['county_txt']."\r\n");
if($rowCounter == 2500) {
fclose($fp);
if($startID) {
rename("{$startID}.txt", "Red-#{$fileCounter}-".date("Ymd")."-{$rowCounter}.txt");
$startID = md5(microtime(1));
}
$fp = fopen("{$startID}.txt", "w");
$rowCounter = 0;
$fileCounter++;
}
}
// Save last file
fclose($fp);
rename("{$startID}.txt", "Red-#{$fileCounter}-".date("Ymd")."-{$rowCounter}.txt");
?>
On that note, don't use mysql_* functions. Instead, use mysqli at the very least, or PDO.
Not really sure what you are trying to do here, but it seems you are making things way harder than need be. In essence, it seems that you need to work with a two-dimensional array. So why not just query the database and read the data into a 2-D array right off the bat rather than jump through all these extra hoops (i.e. functions to determine unique array values and such)?
So you code might look something like this:
$county_array = array()
while ($row = [YOUR DATABASE ROW FETCHING MECHANISM HERE]) {
$county_array[$row['county_name']][] = $row; // you can change $row here to whatever data you actually need to store.
}
$limit = 2500;
foreach ($county_array as $county_name => $county_array) {
$temp_array = array();
$i = 0;
foreach ($county_array as $item) {
$temp_array[] = $item;
$i++;
if ($i === $limit) {
// we reached file limit, so write it to file code omitted for this
$temp_array = array();
$i = 0;
}
}
if (count($temp_array) > 0) {
// there are still items in temp array so write them to file code omitted for this
}
}
If you actually order by country name in your query and detect for changes to the value when reading county names out (and thus starting a new file), you could actually write directly into files in your loop that reads from the DB saving yourself memory overhead.
i m trying to do a loop but get stacked ,
i have a function that convert facebook id to facebook name , by the facebook api. name is getName().
on the other hand i have an arra with ids . name is $receivers.
the count of the total receivers $totalreceivers .
i want to show names of receivers according to the ids stored in the array.
i tried every thing but couldnt get it. any help will be appreciated . thanks in advance.
here is my code :
for ($i = 0; $i < $totalreceivers; $i++) {
foreach ( $receivers as $value)
{
echo getName($receivers[$i]) ;
}
}
the function :
function getName($me)
{
$facebookUrl = "https://graph.facebook.com/".$me;
$str = file_get_contents($facebookUrl);
$result = json_decode($str);
return $result->name;
}
The inner foreach loop seems to be entirely redundant. Try something like:
$names = array();
for ($i = 0; $i < $totalReceivers; $i++) {
$names[] = getName($receivers[$i]);
}
Doing a print_r($names) afterwards should show you the results of the loop, assuming your getNames function is working properly.
Depending of the content of the $receivers array try either
foreach ($receivers as $value){
echo getName($value) ;
}
or
foreach ($receivers as $key => $value){
echo getName($key) ;
}