在PHP中更改数组键值

时间:2021-03-23 22:08:37

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?.

我需要改变键值。我怎样才能做到这一点?。

2 个解决方案

#1


4  

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

#2


0  

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

array_values()函数返回一个包含数组所有值的数组,并重置所有键。你可以这样做

$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.

在您身边试用此代码。

#1


4  

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

#2


0  

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

array_values()函数返回一个包含数组所有值的数组,并重置所有键。你可以这样做

$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.

在您身边试用此代码。