Best unofficial Apache Server developers community
Username
Forgot password?
Sign in with Twitter account
Sign in with Facebook account

Mysql order by photo_id desc and shuffle after

0

39 views

I want to select the most recent 12 rows from a table, but then shuffle the order.

So i cant use ORDER BY RAND() becouse that would just randomly pick some rows and not the most recent 12 rows.

I was thinking something like this, but it didnt work out as planned:

    $artig_photos = mysql_query("

    SELECT photo_id, photo_name
    FROM `migo_artig_photos`
    WHERE (
        photo_deleted=0 AND photo_type=2
    )
    ORDER BY photo_id DESC
    LIMIT 12;

");

while ($row = mysql_fetch_array($artig_photos)) {
    $artig_shuffled[$row['photo_id']] = $row['photo_name'];
}   

shuffle($artig_shuffled);

later when i do:

foreach ($artig_shuffled as $key => $value) {
}

i excepted the key to be photo_id and the value to be photo_name with the correct relation between them, guess i was wrong.

Any tips about how to solve this problem? Maybe my approach isnt good at all.

Best of regards, Alexander

asked June 14, 2011 9:15 pm CDT
posted via StackOverflow

3 Answers

1
 

You could put them all in an array in PHP, then randomize the order of that array with shuffle(), or make the query to select the most recent 12 a sub query, then randomize the results with the outer query. using mysql_fetch_assoc() rather than _array() should help things remain clear after shuffling.

answered June 14, 2011 9:25 pm CDT
0
 

You could use a subquery:

SELECT * FROM (
  SELECT `migo_artig_photos`.`photo_id`,
         `migo_artig_photos`.`photo_name`
  FROM   `migo_artig_photos`
  WHERE  `migo_artig_photos`.`photo_deleted` = 0 AND
         `migo_artig_photos`.`photo_type` = 2
  ORDER BY photo_id DESC
  LIMIT 12) `top_12_migo_artig_photos`
ORDER BY RAND();

answered June 14, 2011 9:25 pm CDT
1
 

PHP's shuffle() function removes any existing keys from your array:

Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys.

This function is best used with numerically indexed arrays. A quick approach would be to just write your own shuffle function that works on associative arrays. I found this one on a previous Stack Overflow post:

function shuffle_assoc($list) { 
  if (!is_array($list)) return $list; 

  $keys = array_keys($list); 
  shuffle($keys); 
  $random = array(); 
  foreach ($keys as $key) { 
    $random[] = $list[$key]; 
  }
  return $random; 
} 

Link to the original:

PHP Random Shuffle Array Maintaining Key => Value

answered June 22, 2011 4:24 am CDT

Your answer

Join with account you already have


Sign in with Twitter account
Sign in with Facebook account
Sign in with Google Friend Connect

Preview
Similar questions
Php mysql asc/desc order
February 22, 2011
Array and DESC LIMIT
March 25, 2011