/*更改索引而不重写整个表并保持在同一位置。
*/
<?php
function change_index(&$tableau, $old_key, $new_key) {
$changed = FALSE;
$temp = 0;
foreach ($tableau as $key => $value) {
switch ($changed) {
case FALSE :
if ($key == $old_key) {
$tableau[$new_key] = $tableau[$old_key];
unset($tableau[$old_key]);
$changed = TRUE;
}
break;
case TRUE :
if ($key != $new_key){
$temp= $tableau[$key];
unset($tableau[$key]);
$tableau[$key] = $temp;
break;
}
else {$changed = FALSE;} }
}
array_values($tableau); }
$tableau = array(1, 2 , 3, 4,5, 6, 7, 8, 9, 10);
$res = print_r($tableau, TRUE);
$longueur = strlen($res) -1;
echo "旧数组:\n" . substr($res, 8, $longueur) . "\n" ;
change_index ($tableau, 2, 'number 2');
$res = print_r($tableau, TRUE);
$longueur = strlen($res) -10;
echo "新数组:\n" . substr($res, 8, $longueur) . "\n" ;
?>