du512926 2013-05-28 19:31
浏览 27
已采纳

Codeigniter 2.1,PHP - 从键值对中获取随机数组

I have query from which I need to take random values (random rows) and limit to, lets say, 5 results and subtract them from main array (query). How can I do this?

This is query function:

public function galerija_jedna_slike()
    {
        $galerija = $this->db->order_by('id_galerija', 'RANDOM')->limit(1)->get($this->table)->row();
        $q = " SELECT * FROM galerija_slike
                LEFT JOIN galerije
                ON galerija_slike.galerija_id = galerije.id_galerija
                WHERE galerija_id = $galerija->id_galerija ";
        return $this->db->query($q)->result_array();
    }

I managed to get random values, and now I need to remove those values from the main array. Function:

function array_random_assoc($arr, $num = 1) {
        $keys = array_keys($arr);
        shuffle($keys);

        $r = array();
        for ($i = 0; $i < $num; $i++) {
        $r[$keys[$i]] = $arr[$keys[$i]];
        }
        return $r;
    }
  • 写回答

3条回答 默认 最新

  • duanshangying5102 2013-05-28 19:46
    关注

    Load the entire table:

    $gallery =  $this->db->query("SELECT * FROM gallery;");
    

    Let choose five random rows from gallery:

    $max_items = 5;
    $num = $query->num_rows();
    $row = $query->row(rand(0, $num - 1));
    $minus = array(); //store the ids to include
    
    for ($i = 0; $i < $max_items; $i ++)
        $minus[] = $gallery ->row(rand(0, $num - 1));
    

    Iterate the gallery to build two arrays, 1. Gallery minus random rows 2. Random rows

    $data = array();
    foreach ($gallery ->result() as $row)
    {
        if (in_array($row->id, $minus))
            $data['random'][] = $row
        else
            $data['gallery'][] = $row
    }
    

    Now, the array $data['gallery'] has all the items without the randon rows. And $data[random] is an array containing the random rows.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘