Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 选择一行的随机场并相应地更新它_Php - Fatal编程技术网

Php 选择一行的随机场并相应地更新它

Php 选择一行的随机场并相应地更新它,php,Php,我需要构建一个函数来选择字段的一个随机行,但不选择任何行 假设这些字段被调用 id, user, one, two, three, four,five,six 1,'jack',0,0,0,1,0,0 调用函数时,我需要更新以下字段之一:one、two、three、four、five、six,其值为“0”,并将其设置为“1”。因此,一个字段不能选择多次。实际上,有10多个字段需要这种处理。顺序必须是随机的 我仍在努力找出逻辑,但不要写太多的行。有什么建议吗?我从来没有听说过在任何数据库中选择随

我需要构建一个函数来选择字段的一个随机行,但不选择任何行

假设这些字段被调用

id, user, one, two, three, four,five,six
1,'jack',0,0,0,1,0,0
调用函数时,我需要更新以下字段之一:
one、two、three、four、five、six
,其值为“0”,并将其设置为“1”。因此,一个字段不能选择多次。实际上,有10多个字段需要这种处理。顺序必须是随机的


我仍在努力找出逻辑,但不要写太多的行。有什么建议吗?

我从来没有听说过在任何数据库中选择随机列的方法,但是如果值都是1或0,为什么不将它们全部放在一个中呢?这样,您将拥有一个类似
1010001000001001
的字符串,其中每个数字表示一个不同的“列”。您可以使用PHP操作它并更新数据库。

怎么样:

    function Z($id){
    $array =array('one','two','three'); //field names
     shuffle($array);//radnoise the array

     $update='';
     foreach($array as $k => $a){
        if($k==0){
            $update .="'$a'=1,";//first random field is 1

        }else{
            $update .="'$a'=0,";//all other fields are 0
        }
    }

    $update=rtrim($update,",");//remove last comma

    $q="update table set $update where id=$id";
return $q; //for testing, otherwise run query
}

echo Z('4'); //test it
//版本2

function ZZ($id){
    $array =array('one','two','three'); //field names
     $value=$array[array_rand($array)];
    $q="update table set '$value'=1 where id=$id";
return $q; //for testing, otherwise run query
}

echo ZZ('4'); //test it

实数代码实数结构比伪“随机”更有用,这意味着一行中可以选择一列三到四次。(掷骰子看看原因。)也许你想?@Catcall一旦选择一个字段,它将被设置为1,因此不能选择两次。但我甚至不喜欢洗牌()…有趣。我喜欢它,但是所有其他字段都不是0或设置为0。最终该行的所有字段都将为1.ok,然后只需更新随机选择的1个字段名。在这种情况下,应该使用array_rand()。如果返回的字段已经是1怎么办?我可以再做一次array_rand,但如果这个也是1呢?如果它们都是1呢?听起来你必须先选择才能得到非“1”字段。我想不出用一个问题就能解决这个问题。我从来没有想过。我想每个字段都有一个单独的字段更方便。