0

I have the following code that pulls data off a mysql database and stores it in a 2D array ($rows). But after I print the contents with a foreach loop I just can't seem to be able to use that array again! Can't figure out how to reset it (printing it again just gives garbage)!

$result = $database->query('SELECT * FROM testtable ORDER BY timestp DESC;');
		
		$rows = array(array());

		while ( $tmp = $db->fetch_assoc( $result ) )
		{
			$rows[] = $tmp;
		};
		
		foreach ( $rows as $rows)
		{
			echo '<br />';
			echo $rows['id']." --> ".$rows['timestp']." --- ".$rows['val'];
		}

Using the array first time works for any operation, btw. Help needed!

I found this following bit of code but it doesn't seem to work as I wish:

function Array_Dimensional_Reset(&$arrRef) {
			foreach ($arrRef as $key=>$val) {
				if (is_array($val)) {
					$this->Array_Dimensional_Reset($val);
					reset($arrRef[$key]);
				}
			}
		}

Thanks.

2
Contributors
3
Replies
5
Views
8 Years
Discussion Span
Last Post by edwinhermann
0

foreach ($rows as $rows) is invalid - you can't use the same variable name twice.

Try this:

$result = $database->query('SELECT * FROM testtable ORDER BY timestp DESC;');
		
$rows = array(array());

while ( $tmp = $db->fetch_assoc( $result ) )
  {
  $rows[] = $tmp;
  }
		
foreach ( $rows as $row)
  {
  echo '<br />';
  echo $row['id']." --> ".$row['timestp']." --- ".$row['val'];
  }

reset($rows);

Edited by edwinhermann: n/a

0

Woohoo, works like a charm! Thanks! :)

I'm confused now as to what the fuss is about reset()ing multidimensional arrays though.

0

Woohoo, works like a charm! Thanks! :)

I'm confused now as to what the fuss is about reset()ing multidimensional arrays though.

You're welcome.

You can use next() prev() or current() to walk through the array, by advancing a pointer. reset() resets the pointer back to the beginning.

If you don't use those it's unlikely that you need to reset() the array.

By the way, foreach() automatically resets the pointer to the beginning of the array, so reset() is not needed before it.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.