Re-sorting array via array keys?
I have two arrays, $country
and $redirect
with each entry corresponding with it's exact counterpart e.g. $redirect[1]
and $country[1]
.
After un-setting values throughout the array, I might be left with, for example, an array where only $var[4]
and $var[2]
are set. I want to re-assign array keys from 0 upwards, so that $var[2]
would have it's key re-assigned to $var[0]
and $var[4]
re-assigned to $var[1]
.
Essentially the sort()
function, but sorting by current array key, as oppose to the numeric/string value of an array.
Is this possible?
Any answers or advice would be greatly appreciated ;)!
UPDATE:
I've attempted to use both ksort()
and array_values()
, however I'm not sure they're really what I need, as I plan on using the size_of()
function.
My code:
$var = array(2 => "value_1", 4 => "value_2", 6 => "value_3");
ksort($var);
for($i = 0, $size = sizeof($var); $i < $size; $i++) {
$var[$i] = "foo";
}
var_dump($var);
Returns:
array(5) { [2]=> string(3) "foo" [4]=> string(7) "value_2" [6]=> string(7) "value_3" [0]=> string(3) "foo" [1]=> string(3) "foo" }
Any addi开发者_如何学Ctional ideas/answers on how I could get this to work would be greatly appreciated!
Use array_values()
(returns "sorted" array):
$var = array(2 => "value_1", 4 => "value_2", 6 => "value_3");
$var = array_values($var);
for($i = 0, $size = sizeof($var); $i < $size; $i++) {
$var[$i] = "foo";
}
var_dump($var);
精彩评论