我有以下方法:array_splice删除多个项目
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++;
}
}
完美!并且使用'1'而不是'-1'也有帮助! – 2013-05-04 20:32:18
是的,这是一个小提示。我只是再次编辑,一个代码示例留下了一些更多的提示:不要为每个方法调用创建新的Database(),而是使用私有成员来存储它。此外,它显示了一个小技巧来创建可能在您的情况下工作的数组值,以使数据库查询更易于调用。 – hakre 2013-05-04 20:34:18
'$ values'等于'Array ( [0] => 201305042040 )'当我这样做时。 – 2013-05-04 20:40:04