Jump to content

[SOLVED] reversing an array


damian0612

Recommended Posts

How can I reverse the results of an array in php?

 

I have queried mysql:

 

$result = mysql_query("            
SELECT * 
FROM fixtures
WHERE result != ''
ORDER BY date DESC
LIMIT 6", $connection);

 

Now, I want to reverse the results? I can't do it in the query as it will return many rows if I didn't limit it and these 6 are the ones I need, therefore if I ordered by ASC it would get a different 6 which I dont want.

 

I have tried:

 

foreach (array_reverse($result) as $result2) { 
   print "$result2";

 

But I get errors. Can anyone help?

 

Thanks

Damian

Link to comment
https://forums.phpfreaks.com/topic/155617-solved-reversing-an-array/
Share on other sites

try that

<?php
$result = mysql_query("SELECT * FROM fixtures WHERE result != '' ORDER BY date DESC LIMIT 6", $connection);
$results = array();
for ($i = (mysql_num_rows($result) - 1); $i > 0; $i--) {
	mysql_data_seek($result,$i);
	$results[] = mysql_fetch_assoc($result);
}
?>

 

note: its untested.. as I just wrote it, but if it doesn't work just tweak it a bit, thats along the lines of what you need :)

Think I'd rather stick with a regular while loop and array_reverse afterwards.  Seems a lot more cleaner/clearer in intention if reading, imo.

I know, thats what I was originally going to formulate for him, however, using the while loop, then array reverse, will ofcourse do the same operations double, instead my way, you get the data, and put it in the right place, at the same time

Thanks for your help, got it solved:

 

//temporary results array 
$results = array(); 

//our query 
$sql = "SELECT * FROM fixtures WHERE result != '' ORDER BY date DESC LIMIT 6"; 
$query = mysql_query($sql); 
while($result = mysql_fetch_assoc($query)){ 
  //store the results in an array 
  $results[] = $result; 
} 

//reverse our array 
$fixtures = array_reverse($results); 

//print our array 
foreach($fixtures as $fixture){ 
  print_r($fixture); 
} 

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.