我有以下方法:
public function selectFinal(){
$db = new Database();
for($i = 0; $i < 5; $i++){
$key_id = mt_rand(0, count($this->candidates) - 1);
$itm = $this->candidates[$key_id];
$host = $itm["host"];
$item = $itm["item"];
$db->query("insert ignore into trends (trend_id, host, item) values (?, ?, ?)", array($this->nextId, $host, $item));
array_splice($this->candidates, $key_id, -1);
print_r($this->candidates);
$this->nextId++;
}
}
对于print_r()
我得到这个输出:
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => IytNBm8WA1c
)
[1] => Array
(
[host] => www.youtube.com
[item] => kffacxfA7G4
)
[2] => Array
(
[host] => www.youtube.com
[item] => kXYiU_JCYtU
)
[3] => Array
(
[host] => www.youtube.com
[item] => 7AVHXe-ol-s
)
[4] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => IytNBm8WA1c
)
[1] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
Array
(
[0] => Array
(
[host] => www.youtube.com
[item] => qkM6RJf15cg
)
)
该数组将从其中包含 5 个或更多项目开始。我想做的是从数组中选择一个随机项目并将其插入数据库,然后将其从数组中删除。我想这样做 5 次以从数组中获取 5 个随机项。但由于某种原因,它选择 1 然后从数组中删除 3 个项目,我不知道为什么(如代码的第二部分所示)。
编辑:最终工作结果
public function selectFinal(){
$db = new Database();
for($i = 0; $i < 5; $i++){
$key_id = mt_rand(0, count($this->candidates) - 1);
$itm = array_values(array_merge([$this->nextId], array_splice($this->candidates, $key_id, 1)[0]));
$db->query("insert ignore into trends (trend_id, host, item) values (?, ?, ?)", $itm);
$this->nextId++;
}
}