我遇到了从循环中的数组切片的问题。我想要做的是遍历一个数组,每天从数组中返回3个不同的部分。所以例如第一天应该返回0,1,2天2应该返回3,4,5等...我使用array_slice()
并且它适用于第一次迭代,但是在后续迭代中,它只返回一个数组中有1个项目。任何帮助将非常感激!!
以下是我目前的情况:
foreach ($days as $day) {
$j = $j + 1;
var_dump("j" . $j);
$activities = array_slice($activities, $j, $number_of_activities);
var_dump("day" . $day);
var_dump($activities);
}
这是var_dump ...
返回的内容string(2) "j1"
string(4) "day1"
array(3) {
[0]=> int(1)
[1]=> int(2)
[2]=> int(3)
}
string(2) "j2"
string(4) "day2"
array(1) {
[0]=> int(3)
}
答案 0 :(得分:1)
我认为它正在做它应该做的事情。您对切片的重新分配活动结果。所以在第二次迭代中,数组有3个元素,你从索引2开始,所以你的切片只有一个元素(最后一个)。我认为你有一个逻辑错误。您可能需要一个临时变量来保存切片而不是覆盖活动。
答案 1 :(得分:0)
我同意克里斯,我将array_chunk()
用于此任务。原因是如果你在循环之外使用array_chunk()
,它是一个完成的函数调用,你可以通过块的索引尽可能多地访问它。在循环中使用array_slice()
意味着每次迭代都会调用函数,这样效率会降低,因此不是最佳实践。
考虑these demos:
演示#1:比所需更多的活动,但没有问题:
$days=[1,2,3];
$activities=['Poker','Blackjack','Omaha','Pinochle','500','Euchre','Canasta','Hearts','Spades','Multitaire'];
$activities_per_day=3;
$activity_sets=array_chunk($activities,$activities_per_day);
foreach($days as $i=>$d){
echo "Day: $d, Activities: ",implode(', ',$activity_sets[$i]),"\n";
}
/*
Day: 1, Activities: Poker, Blackjack, Omaha
Day: 2, Activities: Pinochle, 500, Euchre
Day: 3, Activities: Canasta, Hearts, Spades
*/
演示#2:没有足够的活动来填补最后一天,但没有问题:
$days=[1,2,3];
$activities=['Poker','Blackjack','Omaha','Pinochle','500','Euchre','Canasta'];
$activities_per_day=3;
$activity_sets=array_chunk($activities,$activities_per_day);
foreach($days as $i=>$d){
echo "Day: $d, Activities: ",implode(', ',$activity_sets[$i]),"\n";
}
/*
Day: 1, Activities: Poker, Blackjack, Omaha
Day: 2, Activities: Pinochle, 500, Euchre
Day: 3, Activities: Canasta
演示#3:最后一天没有活动 - 导致问题:
$days=[1,2,3];
$activities=['Poker','Blackjack','Omaha','Pinochle','500','Euchre'];
$activities_per_day=3;
$activity_sets=array_chunk($activities,$activities_per_day);
foreach($days as $i=>$d){
echo "Day: $d, Activities: ",implode(', ',$activity_sets[$i]),"\n";
}
/*
Day: 1, Activities: Poker, Blackjack, Omaha
Day: 2, Activities: Pinochle, 500, Euchre
Day: 3, Activities: <br />
<b>Notice</b>: Undefined offset: 2 in <b>[...][...]</b> on line <b>33</b><br />
<br />
<b>Warning</b>: implode(): Invalid arguments passed in <b>[...][...]</b> on line <b>33</b><br />
*/