问题
Forgive my noobness again. I've got an array with 20+ values in it and I take every 20 to shove in my database and then chop them off the front of the array. I want to restart the array's indexes back to 0 but instead it starts at 20 even when I use array_values. I also tried array_merge(array(), $string) What to do?
if($x%20 == 0){
var_dump($string) // original array
get_string($string, $body, $binary); //puts the 20 string into my db
for($y=0; $y <20; $y++) //done with the 20 so I'm removing them
unset($string[$y]);
array_values($string); //reindex set $string[20] to $string[0] PLEASE!
var_dump($string); // this is suppose to be reindexed
}
Instead I get
array // original array
0 => string '----' (length=25)
1 => string '----' (length=15)
2 => string '----' (length=27)
3 => string '----' (length=22)
4 => string '----' (length=23)
5 => string '----' (length=21)
6 => string '----' (length=26)
7 => string '----' (length=23)
8 => string '----' (length=24)
9 => string '----' (length=31)
10 => string '----' (length=19)
11 => string '----' (length=22)
12 => string '----' (length=24)
13 => string '----' (length=24)
14 => string '----' (length=25)
15 => string '----' (length=12)
16 => string '----' (length=16)
17 => string '----' (length=15)
18 => string '----' (length=23)
19 => string '----' (length=15)
20 => string '----' (length=16)
21 => string '----' (length=27)
array //reindexed array? This was suppose to be [0] and [1]
20 => string '----' (length=16)
21 => string '----' (length=27)
回答1:
I usually do:
$array = array_values($array);
Looks like you got most of the way there - just forgot to assign the new array to the old variable.
回答2:
Assign the return value of the reindexed array back to it:
if($x%20 == 0){
var_dump($string) // original array
get_string($string, $body, $binary); //puts the 20 string into my db
for($y=0; $y <20; $y++) //done with the 20 so I'm removing them
unset($string[$y]);
$string = array_values($string); //reindex set $string[20] to $string[0] PLEASE!
var_dump($string); // this is suppose to be reindexed
}
OR, as Brad suggests replace:
for($y=0; $y <20; $y++) //done with the 20 so I'm removing them
unset($string[$y]);
$string = array_values($string); //reindex set $string[20] to $string[0] PLEASE!
with:
for($y=0;$y<20; $y++)
array_shift($string);
回答3:
I would have a look at array_shift. That may do what you're looking for as you're "popping" them off the array.
EDIT
Also, whenever you're dealing with arrays and loops, it's a good idea to keep conscience of the fact that the array may come up short. That is to say, I strongly suggest not coding the fixed for(... <20 ...)
but use a variable such as $end = (count($array) < 20 ? count($array) : 20);
来源:https://stackoverflow.com/questions/4393541/php-reindexing-an-array