Changing array key value in PHP

2020-04-29 16:13发布

问题:

I have an array like below,

[test] => Array
        (
            [0] => 1
            [1] => 3
            [2] => 5
            [3] => 13
            [4] => 32
            [5] => 51
        )

i need to change this array into like below,

[test] => Array
            (
                [2] => 1
                [4] => 3
                [6] => 5
                [8] => 13
                [10] => 32
                [12] => 51
            )

i need to change the key value. How can i do this?.

回答1:

$newArray = array_combine(
    range(2,count($originalArray)*2,2),
    array_values($originalArray)
);


回答2:

The array_values() function returns an array containing all the values of an array and also it reset all the keys. you can do it as

$arr = array(0 => 1, 1 => 3, 2 => 5, 3 => 13, 4 => 32, 5 => 51);
$count = 1;
$tempArr = array();
foreach ($arr as $key => $val) {
    $tempArr[$count * 2] = $val;
    $count++;
}
var_dump($tempArr);exit;

Try this code at your side.



标签: php arrays key