字符串到数组的转换,array_rand,unset和返回数组到字符串。有捷径吗?

时间:2017-02-18 15:41:13

标签: php mysql arrays string

我正在编制一个电话呼叫页面。其中一个functions我的写作会在选定的时间获取available assistants(saved as assistant_ids)选择一个随机的,将其从列表中删除,然后更新表格。非常直截了当。

我已经为它编写了代码并且它工作得非常好,但是,这段代码使用了很多函数来完成这个过程。而且我觉得我用右脚搔痒我的左耳!

是否有所有这些代码的快捷方式,以后将为服务器节省大量处理?

$assistants = self::get_avail_assists($table, $this->time);
        //Assistants are saved as ids and each one is 18 Char.
        //each one separated with a space
        $assistants_no = strlen($assistants);
            if($assistants_no > 1){
                for($i=0; $i<$assistants_no; $i=$i+18){
                    $assistants_array[$i/18] = substr($assistants,$i,17);
                }
            }

        //select random assistant key
        $rand_assistant_key = array_rand($assistants_array);
        //retrieve selected assistant
        $rand_assistant = $assistants_array[$rand_assistant_key];
        //delete selected assistant from list
        unset($assistants_array[$rand_assistant_key]);

        //clear assistants string
        $assistants = "";
        //recreate assistants string to update
        foreach($assistants_array as $assistant){
            $assistants .= $assistant." ";
        }
        //update database after popping out the random assistant
        $sql = "UPDATE ".$table." SET ".
        "avail_assists='".$assistants."' ".
        "WHERE id='".$this->time."' ".
        "LIMIT 1";
        mysqli_query($sql,etc...

感谢您的时间!

1 个答案:

答案 0 :(得分:0)

假设助理重新输入数据库的顺序无关紧要......

$ass_array=explode(" ",$assistants);  // space-separated string to array

shuffle($ass_array);    // mix it up
$lucky_ass=$ass_array[0];   // save one for whatever usage
unset($ass_array[0]);  // remove the one from the group

$leftover_string_of_asses=implode(' ',$ass_array);  // convert array to space-separated string

...add sql query