【问题标题】:String-to-array conversion, array_rand, unset, and back to array-to-string. Is there a shortcut?字符串到数组的转换,array_rand,未设置,然后返回到数组到字符串。有捷径吗?
【发布时间】:2017-07-08 02:48:38
【问题描述】:

我正在安排一个电话呼叫页面。我正在写的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...

感谢您的宝贵时间!

【问题讨论】:

  • 如果 id 不包含空格,那么您可以使用 php.net/manual/en/function.explode.php 而不是循环。如果您不打算使用它,还要知道为什么要保存 $rand_assistant
  • 另存为存储在变量中
  • @bassxzero 感谢 cmets。现在explode 函数肯定会节省一些循环。我首先使用rand_assistant 对助手公平,变量将是returned 调用函数
  • 您以现在的方式存储数据有什么原因吗?正如我想的那样,如果您使用该表将每个 id 存储在一行中,而不是将所有 id 打包到一行中。可以让事情变得更容易。那么您只需要查询一个可以通过 sql 完成的随机行,然后将结果设置为您的随机助手并启动另一个查询以从表中删除该 id。但这需要以非常不同的方式将数据存储在表中,所以我不知道这是否可以做到。
  • @KitRamos table 包含一个id 所选时间段的时间戳avail_assists 该时间戳处助手的ID .因此,按照您的建议进行操作需要将table 更改为idtimestampassistant。所以基本上更多 rows 来减少 processing

标签: php mysql arrays string


【解决方案1】:

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

$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

【讨论】:

  • 这看起来真的是代码的终极快捷方式。非常感谢您的宝贵时间。 PS:我喜欢你叫他们 ass 虽然 :D
  • 不客气。乐于助人。 (......是的,我忍不住对变量命名)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多