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.

Recommended Answers

All 3 Replies

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);

Woohoo, works like a charm! Thanks! :)

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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.