【问题标题】:mysql order by photo_id desc and shuffle aftermysql order by photo_id desc 并在之后随机播放
【发布时间】:2011-06-15 02:15:54
【问题描述】:

我想从表中选择最近的 12 行,然后打乱顺序。

所以我不能使用 ORDER BY RAND() 因为它只会随机选择一些行而不是最近的 12 行。

我在想这样的事情,但没有按计划进行:

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

稍后当我这样做时:

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

我希望键是photo_id,值是photo_name,它们之间的关系正确,我猜我错了。

关于如何解决这个问题的任何提示?可能我的方法一点都不好。

最好的问候, 亚历山大

【问题讨论】:

  • shuffle 不保留数组键。

标签: php mysql


【解决方案1】:

您可以将它们全部放在 PHP 中的一个数组中,然后使用 shuffle() 随机化该数组的顺序,或者进行查询以选择最近的 12 个子查询,然后使用外部查询随机化结果。只需使用$items[] = $row; 存储项目,然后使用shuffle($items);并对其进行迭代。您不会在$key 中获得$photo_id,但它仍会在$item['photo_id']

【讨论】:

    【解决方案2】:

    PHP 的 shuffle() 函数从您的数组中删除所有现有的键:

    注意:此函数将新键分配给数组中的元素。它将删除任何可能已分配的现有键,而不仅仅是重新排序键。

    此函数最适用于数字索引数组。一种快速的方法是编写您自己的适用于关联数组的 shuffle 函数。我在之前的 Stack Overflow 帖子中找到了这个:

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

    原文链接:

    PHP Random Shuffle Array Maintaining Key => Value

    【讨论】:

      【解决方案3】:

      您可以使用子查询:

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

      或者,您可以这样做:

      // To shuffle:
      while ( $row = mysql_fetch_array($artig_photos) )
      {
        $artig_shuffled[] = $row;
      }
      
      shuffle($artig_shuffled);
      
      // To display:
      foreach ( $artig_shuffled as $row )
      {
        echo $row['photo_id'];
        echo $row['photo_name'];
      }
      

      【讨论】:

        猜你喜欢
        • 2015-02-26
        • 1970-01-01
        • 2012-03-07
        • 2011-12-22
        • 2013-09-20
        • 2019-06-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多