Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    PHP




Looping Through An Array And Using The Results.


function build_menu() {
$all_li = create_list_items();
$menu = '<ul id="navbar">'
reset($all_li);
while($li = each($all_li)) {
$menu .= $li;
}
$menu .= '</ul>'
echo($menu);
}

I'm trying to move through each item in the #all_li array and add it's contents to the $menu variable. $all_links is filled with string values from the function create_list_items().

I tried (above) using each(), but the output from the function is "ArrayArrayArray" and this has me confused. I think it's giving me this because each() creates an array which includes key values (yes?), which means each() is not the method I need to use.

Can anybody advise me on a method I can use to loop through the $all_links array and add each string to the $menu variable? So far I've tried a for loop, foreach, even attempted an array_walk(), but haven't had any success.




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Looping Results...
I'm writing a simple display page for a bunch of info from a realestate database as an exercise. I've successfully queried and displayed the information in tables, but I want it to keep pulling information from the tables until there are no more left. What i've got only pulls one entry. Code:

Parse Error - Looping Through Results
I am retrieving results from the database and alternating row colors. But here's the dilema. You see, the first field that is diplsayed in each row is the users first and last name. Well, I need to create a link called that will display comments that each user has created when they sign up for their membership.

This link will bring up a pop up window with their comments. This pop up needs to know which "comment" to bring up each user.

I know that might be a little confusing but the code below might help.

// connect to the database
//$db = mysql_connect("database url","username","password") or die("Problem connecting");
//mysql_select_db("database") or die("Problem selecting database");
$query = "SELECT * FROM users ORDER BY fieldname asc";
$result = mysql_query($query) or die ("Query failed");
//let's get the number of rows in our result so we can use it in a for loop
$numofrows = mysql_num_rows($result);
?>
<?
echo "<TABLE BORDER="1" width="800">
";
echo "<TR bgcolor="#CC6633"><TD nowrap0><B><font color="#FFCC00">Alumn Name</TD><TD><B><font color="#FFCC00">Email Address</TD>
.....blah, blah, blah

for($i = 0; $i < $numofrows; $i++) {
$row = mysql_fetch_array($result); //get a row from our result set
if($i % 2) { //this means if there is a remainder
echo "<TR bgcolor="#FFCC00">
";
} else { //if there isn't a remainder we will do the else
echo "<TR bgcolor="white">
";
}
echo "<TD>"<a href="moreinfo.html?=<? echo '$AlumniID ?>>".$row['Firstname']."&nbsp;".$row['Lastname']."</TD><TD>
".$row['EmailAddress']."</TD><TD>".$row['HsGrad']."</TD><TD>".$row['College']."</TD><TD>".$row['Majors']."</TD><TD>.$row['DoingNow']."</TD>
";
echo "</TR>
";
}
//now let's close the table and be done with it
echo "</TABLE>
";
?>

The is where I think it bombs out:
echo "<TD>"<a href="moreinfo.html?=<? echo '$AlumniID ?>>".$row['Firstname']."&nbsp;".$row['Lastname']."</TD>

2D Array Looping
I'm trying to loop through an array that looks like this:

$images[type][2]
$images[size][0]

I've done some research and I tried using two foreach loops, but I couldn't get it to work right. The following PHP gets the first attribute of the array.

Looping Through Array
I am trying to think through the best way to perform the following :

I need to be able to change the CSS stylesheet of a web page when the user clicks a link like "click for larger print"

I understand basically how this is done but I'm wondering if someone could give me a syntax pointer or two.

Looping Through Array
Consider the following array and string:

$trail = array('products/veggies', 'products', 'services/cleaning');
$path = 'products/veggies/1243/more'

I am trying to write a function that matches $path with a value in
$trail. If no match is found, it should chop off "more" and compare
again. Then, chop off "1243" and compare again. Now a match is found:
"products/veggies". The function should return true.

Let's take another example: $path = 'services/industrial/gardening'.
There is no match for $path in $trail. Chopping off "gardening" leaves
"services/industrial". Again, no match. Chopping off "industrial"
leaves "services". No match will be found; the function should return
false.

This is what I have so far:

function in_trail($path) {
global $trail;

while ($path && !in_array($path, $trail)) {
$path = substr($path, 0, strrpos($path, '/'));
}

return $path ? true : false;
}

But this function always returns true! Could someone explain this to
me and tell me how to fix it?

Looping From An Array?
I've wrote this script that will pull the last 6 uploaded results in the database and return them via the function recentlyuploaded()

When I call this function it will contain the data from 6 results but the way I have it coded I am only assigning the first value of that array returned. How can I loop through the array that i returned and assign the 6 results to their respective variables? Code:

Looping An Array
i have a set of radio buttons and a set of checkboxes that have the same names for each group.

ServiceName = radiobutton group
reasons = checkbox group

When the user selects a radio button and/or  one or many checkboxes the value is supposed to be passed into a variable and sent in an e-mail.  the only problem is that the values are not taken.  i have another checkbox that is individual in it's name on the page and the value is passed fine from it.  below is my code. Code:

Looping Through Nested Array
I parse through a xml file and create an array of the data. I now need to loop through all the nested arrays but I'm unsure of how to do this. Code:

Trouble With Looping Through An Array
I am having some trouble with a booking system. What I want to do it is make booked times display in red. Available times in white. Below is my function. It works for no, or one booking. However if you do a second booking everything comes unstuck, its pretty obvious why but I can't figure out any other way to do this. Code:

Looping Thru Array Like For Loop
i want to loop thru this array so that i can read the tagname from 0_filename and put records till 1_filename to insert query and again read from 1_filename to 2_filename and call query again and keep on doing that till the time i see the last n_filename tag Code:

Getting An Error When Looping Multi Array
I have come up with code that works fine on my local machine, but spits an error when it goes live on the site. I can only think it is due to the php version. But, just in case its the code, here is the error line:

foreach($this->details[$code] as $value){
. foreach($value as $option){
. . $spin = $option['option_type'];
. . array_push($totals, $spin);
. } //fe
}// fe

Is there anything wrong with that?

Looping Thru Array And Creating Comma Sep String
I'm trying to loop through the elements of an array and create a comma separated string of the values, and then trim off the last comma. Here's the code I have which only displays the last element of the array in the string: PHP Code:

Looping Database Values To Create An Array
I have a fairly simple php code problem I think, I want to loop values from a mysql database within an array to fill the array. I'v never done this before so your help would be valued if someone had the time.

*denotes where I want to use database values*

Checkbox Array From Form - Shorthand For Looping The VALUES?
I am retreiving values from checkboxes in a form to decide where thumbnails and uploaded images get placed (same image goes in multiple directories). The following code works. But I wonder if there is a shorthand way to output the values in a while statment rather than a bunch of if statements. That is, is there a way to output ALL possible values (e.g., sports, group, 2002 - I have many others) in a loop? PHP Code:

Sorting Sql Results In An Array Using Things Outside The Array To Sort Them?
I'm using PHP to connect to a database full of place names, and their associated post codes, latitude and longitude on the earth. A user types his or her post code into a form, plus a distance (in miles), and the script looks for other area codes (first half of the post code) within that distance.

I can do that fine, but the results are ordered alphabetically by postcode, and I want to order it by the distance. Problem here, is that the distance isn't part of the array taken from the database, it takes the latitude and longitude of the area it's on in the while loop, and calculates the distance between the user's post code and that one, but it's not part of the array, so I can't sort the array using it.

How can I sort it? Can I add the calculated distances to the array, and sort it using sort()? If yes, how do I add them to the array?

Here's the page, just to explain better what the script does: http://navimaker.org/ed/owain/results.php?postcode=gl15&distance=34
Mess around with the postcode and distance vars.

I'd put the source on here too but I'm doing all this over SSH and can't copy & paste very easily .

Populating Array With Mysql Results
I'm returning a result set of one field in a table, and want to populate an array with the results. I can't for the life of me figure out a simple way to do this without using mysql_fetch_array() to cycle through the results, append that to a var, then explode that into a var and pass that. PHP Code:

Displaying Array Results In Table
I'd like to display the results of an array in a table format with the Alias, Alias Destination & Username as column headings & the results underneath. PHP Code:

Store Mysql Results Into An Array
i just started using php. i've used it before as a maintainer. fun stuff. well now i'm the writer. i want to abstract all the DB commands away from myself and all other developers. so i'm writing a function to query the php database from all users of the database and store them into an array as a return value so that i can seperate my database code from my html creation code.

1. is there a way to put all my database functions into a php file and include that file into all my other php pages? similiarly to a #include in C++ or a import package name in Java?

2. my code to run down the fetched results and store them into an array doesn't seem to be working the way i want it to. if i print out the results from the mysql returned fetch the data is fine. however the array seems to print out "Array[elementnumber]" instead of the value. Code:

Evaluating Array And Skipping Certain Results
I'm having a brain freeze on this. I have a script where I am reading
the contents of a file into an array. I have that up and working with no
problem. Then I'm exploding the array using

while ($line = fgets($fd, 4096))
{
$arrayData = explode("-", trim($line));
}

Works fine. But what I want to do now is evaluate arrayData[2] to see if
it contains the integers "00" (that's zero zero) and if it does, I want
it to skip that entry. I know I need to set it up with
if arrayData[2] == "00" {

But I'm drawing a blank on how to get it to skip this entire line in the
final results. There may be multiple instances of this happening in each
file and I want to skip them all.

How Do I Search Two-dimiensional Results Set Array
Here's the pertinent code to get the SQL results. It is generated by
dreamweaver adn I'm trying to learn to code php so I don't depend on DW to
do it for me.

$query_rsSummary = "SELECT sid, Count(wid) FROM plotting GROUP BY sid";
$rsSummary = mysql_query($query_rsSummary, $tableG) or die(mysql_error());
$row_rsSummary = mysql_fetch_assoc($rsSummary);


How do I search the array to see if a certain "sid" has an entry in the
array?

Building Array Of Difft Results For Return
I have 2 functions that I want to call from a subroutine, and then return their results; one result is an array, the other will be an array of arrays. The first will be the information about a product, $product, with values like $product['title'], product['id'], etc.

The second will be an array of arrays, each line of which contains information about an element of the product. I.e., $item[0]['title'], $item[2]['value'], etc. How would I best combine these so I can RETURN the total thing from the function, and then how would I refer to the parts in the calling code? For example, if I said Code:

ODBC: Fetch Results As Associative Array
Will PHP fetch the results of a query using ODBC as an associative array? I know that MySQL does that, but I couldn't find it for ODBC connections.

Taking SELECT Results And Turning Them Into An Array()
Does anyone know how take a mysql select statement and have the results placed into an array? I am returning 1+ rows and want to place those rows into an array so I can run a foreach() for each row and then run another foreach() for each column for each row? Code:

How To Make An Array With Query Results? (Postgresql)
Need help making an array with query results:

$value = $_POST['text'];

$pg = pg_connect('dbname=test user=user password=secret');

$query = "SELECT column FROM information";
$result = pg_query($query);

*** how to create array with $results ***

Query Array, Sort Results And Display In Seperate Tables
The problem I have it breaking out the results and displaying them (broken out) alphabetically in seperate tables. For instance, I have generated (bookmarked) tables, one for each letter (A-Z) and want to display all recordsets with say, last name
beginning with "A" in one 2 column table, "B" in another 2 column table, and so on... each
table would have two columns (with 2 background colors alternating), each cell containing values of one recordset.

Even more tricky is if I have an odd number of cells, still generating the last cell with empty values (for asthetics). And can anyone say "sort" (yes, I am nuts)? The ability to sort the whole mess by any column value. I have looked at freeware and other third part apps, but they can only do what I already can do (mine is actually cleaner) but not as complicated.

Array Results Output On Online As Opposed On Separate Lines
How do i get to echo details on oneline as opposed to the next line.

$car=array("red", "green", "white", "blue", "orange");
foreach $car as $color) {

echo "$color<BR/>";

I dont want the results on separate lines but on the same line with commons...

Pushing Data Into A Multi-dimensional Array From Mysql Results
First, A result array I'd want to get could look like this:

$chart['chart_data'] = array (
array ( "Region A", 10,12,11,15,20,22,21,25,31,32,),
);

The first is "Region A" and the rest is just int's that I'd pull from the db, so to set it I'd do this:

$chart [ 'chart_data' ][ 0 ][ 0 ] = "Region A";

But the problem is when I want to insert the data in the while loop (like the 10,12,11,15...), I've tried array_push but it's not working, maybe it doesn't work with multi-dimensional arrays? Anyways, here.'s what I tried, the following inside the "while" to loop the mysql results with mysql_fetch_assoc:

while($r=mysql_fetch_assoc($res)) {
   
     $chart [ 'chart_data' ][ 0 ][ 0 ] = array_push($chart['chart_data'][0][0], $r['wght']);
     // the above line is where I have problems    ^^
}

What I want is on each loop to insert the fetched data inside the array so that it gives what I gave first at the top, but what I've written above doesn't work, it gives me a warning saying "first argument must be an array" which seems to be one, but anyway, anybody know how to do this?

Search Brings Back Different Results Or Sometimes No Results
The problem Iv got is that when searching the site - it brings back different results or sometimes no results. For example: "i026", "i 026" and "026" do not bring back results for "I-026" which is the correct model number. Any ideas on how to make it search more variations or of a "Did you mean... I-026" script?

While Looping.
This function builds a single table that displays a small weekly calendar to display how many records have been entered into my dbase talbe...

i need to show another table with separate queries above this one...

i tried to just duplicate the table, using a while statement, just to make sure i can display two tables, with slightly different queries, but to no avial....would anyone be able to show me the correct syntax to do that?

Code:

Looping In Php
I have a parent/child table. The basic setup is as follows:
The parent table is called load sheet. It has fields such as Tripno,
carrier, loaddate, etc.The child table contains the actual stop offs, in other words the shipper, load city, load state,etc. If a pick then shipper, otherwise a consignee. I have no problem with this parent child table setup.
Here's the problem:

Looping
I am trying the following: I have a ID field in my database wich is displayed in a table.
I want the ID displayed with the link to the ID number. The loop looks like this:

While ($r = mysql_fetch_array($result))
$id = $r[ID];

When I echo that into the table I get the numbers. I want the numbers displayed as a link in the table with the ID variable set to the number for parsing on to the script that gets the record. I have done this futher more:

$ID = "<a href=1.php>". $r[ID]."</a>";

The above links the ID number to the 1.php script but does not parse the $ID to the script.

Looping...
I know how to loop an event a certain number of times, but I cannot figure out how to make the number of times an option. Basically I want to have the form with an option to select the number of times the event happens. Code:

Help With A Looping Function
I have a function that I want to use as a hit counter. Everytime this function is accessed I want a counter to increase by 1.


Code:
function display_articlepart($articlepassed, $infotoreturn, $errorcode) {
// displays a single article
// usage: display_articlepart(selected article id, info to return, $errorcode)
// info to return can be any of these: id artcategory artcreationdate artauthor artauthoremail arttitle artthumbnail arttext arthits

global $tableforarticles;

db_connect($errorcode);

$query = "SELECT * FROM $tableforarticles WHERE id=$articlepassed";
$result = mysql_query($query);

if ( $row = @mysql_fetch_array( $result ) ) {
$id=$row['id'];
$artcategory=$row['artcategory'];
$artcreationdate=$row['artcreationdate'];
$artauthor=$row['artauthor'];
$artauthoremail=$row['artauthoremail'];
$arttitle=$row['arttitle'];
$artthumbnail=$row['artthumbnail'];
$arttext=$row['arttext'];
$arthits=$row['arthits'];

}
else
echo "No items found";

// increment hit counter by 1
mysql_query("UPDATE $tableforarticles SET arthits = arthits+1 WHERE id=$articlepassed");

mysql_close();

// return info

switch( $infotoreturn ) {
case id:
echo "$id"; break;
case artcategory:
echo "$artcategory"; break;
case artcreationdate:
echo "$artcreationdate"; break;
case artauthor:
echo "$artauthor"; break;
case artauthoremail:
echo "$artauthoremail"; break;
case arttitle:
echo "$arttitle"; break;
case artthumbnail:
echo "$artthumbnail"; break;
case arttext:
echo "$arttext"; break;
case arthits:
echo "$arthits"; break;
default:
break;
} // end switch

} // end display_article



The problem is, whenever I call this function, the hits increase by 8 instead of 1.

The mysql query that increments the hit counter,

Code: mysql_query("UPDATE $tableforarticles SET arthits = arthits+1 WHERE id=$articlepassed");

is out of any loop, so why is it running 8 times and increasing the counter 8 times?

Looping Too Many Times
I can't seem to get this loop working properly.
Here is the script:

String Looping?
I am doing user authentication, and I need to find out if the username they chose starts with a number. What is the best way to go about that, is there anything built in to PHP4 to help?

Looping Eating 100 Per Cpu
I've got a while loop thats iterating through a text file and pumping the
contents into a database. the file is quite large (over 150mb).

the looping causes my CPU load to race up to 100 per cent. Even if i remove
the mysql insert query and just loop through the file , it still hits 100
per cent CPU. This has the knock on effect of slowing my script down so
that mysql inserts are occuring every 1/2 second or so.

here's my script:

Looping Through A Query
I am new to PHP and am wondering how to loop through a query in order to avoid delimiters. Below is how I have been doing it in Cold Fusion and was wondering if anyone could help translate this into something similar in PHP.

Bellow is a selection of the fields followed by the table name (verticalfiles) and then the field being searched (name) with the looping of the field following.

SELECT id, name, see, seealso, type, scrapbook
FROM verticalfiles
WHERE name is not null
<CFLOOP LIST="#name#" DELIMITERS=" " INDEX="nameloop">
AND name LIKE '%#nameloop#%'
</CFLOOP>
Order by name

Looping Error
Can anybody explain why this script doesn´t work. It takes ages to load and it doesn´t load everything. I made it for the following purpose. I have a database with 440 Dutch soccerplayers. There is a game where they can earn points. Those points are on another page. I want to load this page in an array and compare all my players with the lines on that site. If a player from my database is in a line on the other site, I filter the points from the other site, and print it on mine. PHP Code:

Looping Within An IF Condition.
I have a counter on my site to log visits. It works well but I've noticed that a lot of visits come from web crawlers so I'm getting counts higher then what it should be. So I put an if statement around my counter code like so..PHP Code:

Looping From A Fetcharray()
I have a SQL query that returns all company names containing a user
defined keyword. I store all this information using: $listings =
mysql_fetch_array($result);

That query works fine, as I am able to see the first company. What I
need to do, is loop through the array, displaying each company name. I
have the code to write the company name to the screen. I am just
trying to figure out how to do the loop. My beta attempt:

(Not shown is that I have used $NumRows to catch the number of rows
contained in $result)

for (x=0, x<=$NumRows, x++){
echo $listings['company_name'];
}

Looping Until Today
I want to loop through dates, stopping at the current date

I set the enddate like this
$enddate=date('Y-m-d');

which prints out as &#55614;&#57158;-04-01'

$l['cc_startdate'] comes from a DB with the column in date format

but when i do
for ($dl=$l['cc_startdate'];$dl < $enddate;$dl++)
{
print $dl;
blah

}

Looping A Result
Im new to PHP and MySql, Im trying to setup a really basic news script for me to use for my site 2design4.com. PHP Code:

Looping Problem
I am having a looping issue, when i execute this code I get a total count of all items at the end of each echo.. Code:

Looping Inserts
In a vain attempt to stop me banging my head against the wall, does anyone have any insights why I cant (go and do something less boring instead...) use a for loop (or any loop for that matter) to get some data from one table and insert it into another? Code:

Looping A Query
I have a cron that updates a field to "yes" where another field says "1", example:

user_id | validate | approve
1         | 1          | yes
2         | 0          |
3         | 0          |
4         | 1          | yes

At the moment I run it every hour and it updates just the first one,

so

UPDATE table SET `approve`= 'yes' WHERE validate = '1';

How do I do it to ALL of them with validate=1?

Add New Table Row While Looping
I want to display 4 images in a <td> from a database.  Once the loop gets to 4 images I want to start the 5th one on a new line.  Can someone help me with this.  This is what I have so far (obvisously it keeps creating new <td>, but no <tr>... Code:

Looping Throught Two Different Arrays
I have two arrays:
PHP Code:

Looping In A Switch Statement
Does anyone know if this is possible, I am trying to iterate sections out of a mysql DB, I am getting a parse error..not sure if this CAN be done.

Performance, Functions And Looping
Has anyone benchmarked the overhead of calling functions in PHP? As an example, let's say I have a function that takes a string as an argument. If this string is zero length, I want to return an empty string right away. Would I gain any time if I put the zero length test before calling the function?


Copyright © 2005-08 www.BigResource.com, All rights reserved