bcosca / fatfree

A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!
2.66k stars 446 forks source link

Add random sorting to Jig mapper #1238

Open m0x3 opened 2 years ago

m0x3 commented 2 years ago

File /lib/db/jig/mapper.php My variant is

         protected function sort($data,$cond) {
        if($cond == '_random') {
            $keys = array_keys($data);
            shuffle($keys);
            $random = array();
            foreach ($keys as $key)
                $random[$key] = $data[$key];

                        return $random;
        }

        $cols=\Base::instance()->split($cond);
        uasort(
            $data,
            function($val1,$val2) use($cols) {
                foreach ($cols as $col) {
                    $parts=explode(' ',$col,2);
                    $order=empty($parts[1])?
                        SORT_ASC:
                        constant($parts[1]);
                    $col=$parts[0];
                    if (!array_key_exists($col,$val1))
                        $val1[$col]=NULL;
                    if (!array_key_exists($col,$val2))
                        $val2[$col]=NULL;
                    list($v1,$v2)=[$val1[$col],$val2[$col]];
                    if ($out=strnatcmp($v1,$v2)*
                        (($order==SORT_ASC)*2-1))
                        return $out;
                }
                return 0;
            }
        );
        return $data;
    }

do it like this, or please add your own better way random sorting

Blue3957 commented 2 years ago

I wouldn't really consider shuffling to be a way to sort things. If I needed a shuffle method on my mappers, I'd probably just add one.

joseffb-mla commented 2 years ago

I'd want to keep with the f3 mantra and keep things light. That being said, if I needed to randomize the order I would do that in my app not the core.