FRIHOSTFORUMSSEARCHFAQTOSBLOGSDIRECTORY
You are invited to Log in or Register a Frihost Account!

php multidimension array question

 


ammonkc
I have a multidimension array, which is just a result set from a mysql query, that I'm looping through. How do I get data out of an iteration that has already been passed in the loop? I'm trying to do this

Code:

$result = mysql_query("SELECT id,date from mytable");
$n = mysql_num_rows($result);   //returns 6 rows
$count = 0;
while($row = mysql_fetch_array($result, MYSQL_ASSOC) {
     echo $row[$count-1]['date']; //this should return the date from the previous row
}//end for loop


or the same type of thing without a loop would be:
Code:

$result = mysql_query("SELECT id,date from mytable");
$n = mysql_num_rows($result);   //returns 6 rows
$row = mysql_fetch_array($result);

echo $row[3]['date'];  //should show the date for row 3 in db

SlowWalkere
Unfortunately, mysql_fetch_array doesn't quite work that way, so you'll have to work around it a bit to get the result you want.

When you retrieve information from a database, it's in a kind of two-dimensional array. But the only way to access it is to use one of the fetch functions, which will return the next record from the select statement in the form of a one-dimensional array (with each element named after a column in the record's table).

Each time you use the fetch function, $row gets written over with the next row. So you can't simply look back to the previous row... it's gone.

One way to get around this, which I've used in the past, is to cycle through the information returned from the database and create your own 2-d array. Like...
Code:
$resArray = array();

while ($row = mysql_fetch_assoc($result))
    $resArray[] = $row;


Now, $resArray will be a two-dimensional array like you want, and you can iterate through it and access two different rows at the same time.

- Walkere
hexkid
ammonkc wrote:
How do I get data out of an iteration that has already been passed in the loop?


Don't iterate the result set. Use the function mysql_result() with appropriate parameters.
Related topics

php or python question about some processing.
array question
Php while array problem
PHP IP Ban
How To : Improve Your PHP Programming

Tutorial: PHP Installed Modules Dynamic Reference Tool
PHP MySQL Commands Question
php/HTML pages question
How to create a php files that contain a image ?
handling the $_POST array

PHP Mysql admin area? please help
[PHP] Problem with Dynamic Sig's Font Color
How to write array in JS?
Php $_POST
PHP.ini and PHP session maxlifetime question
Reply to topic    Frihost Forum Index -> Scripting -> Php and MySQL

FRIHOST HOME | FAQ | TOS | ABOUT US | CONTACT US | SITE MAP
© 2005-2007 Frihost, forums powered by phpBB.