Jump to content

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

yeah I'm not arguing that ^^ is probably more efficient on the processor...but I think this is one of those cases if I were coding it, I'd sacrifice that smidgen of efficiency for readability.

 

edit: I mean, we are talking about a 6 row query...

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

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.