<?php

namespace addons\csmtable\library\xcore\xcore\utils;


/**
 * Random的工具封装类
 * 关于RandomRow和RandomKey,以数组[a:a001,b:b002]为例,RandomRow=a001,RandomKey=a
 */
class XcRandomUtils
{
    /**
     * 取随机记录
     *
     * @param array $rows
     * @param int $rowCount 取记录数
     * @return array
     */
    public static function randomRows($rows, $rowCount)
    {
        if (count($rows) <= $rowCount) {
            return $rows;
        }


        $list = [];
        $indexs = array_rand($rows, $rowCount);
        if ($rowCount == 1) {
            return [$rows[$indexs]];
        }
        foreach ($indexs as $index) {
            $list[] = $rows[$index];
        }
        return $list;
    }
    public static function randomRow($rows)
    {
        if (count($rows) == 0) {
            return null;
        }
        if (count($rows) == 1) {
            return array_shift($rows);
            //return $rows[0];
        }
        $list = static::randomRows($rows, 1);
        return $list[0];
    }


    public static function randomKeys($rows, $rowCount)
    {
        $sr = [];
        if (count($rows) <= $rowCount) { 
            foreach($rows as $key=>$value){
                $sr[] = $key;
            }
            return $sr;
        }

        $sr = array_rand($rows, $rowCount);
        if ($rowCount == 1) {
            return [$sr];
        }
        return $sr;
    }
    public static function randomKey($rows)
    {
        if (count($rows) == 0) {
            return null;
        }
        if (count($rows) == 1) {
            foreach($rows as $key=>$value){
                return $key;
            }
        }
      
        $index = static::randomKeys($rows, 1);
        return $index[0];
    }
}
