开发者

Change values in first key from 0 to count(array) - 1

开发者 https://www.devze.com 2022-12-25 06:46 出处:网络
Ok, I have an array like so: $myArray[32][\'value\'] = \'value1\'; $myArray[32][\'type\'] = \'type1\'; $myArray[33][\'value\'] = \'value2\';

Ok, I have an array like so:

$myArray[32]['value'] = 'value1';
$myArray[32]['type'] = 'type1';
$myArray[33]['value'] = 'value2';
$myArray[33]['type'] = 'type2';
$myArray[35]['value'] = 'value3';
$myArray[42]['value'] = 'value4';
$myArray[42]['type'] = 'type4';

Ok, looking for a quick way to change all numbers in the first key 32, 33, 35, and 42 into 0, 1, 2, and 3 instead. But I need to preserve the 2nd key and all of the valu开发者_如何学编程es. The array is already ordered correctly, since I ordered it using a ksort, but now I need to reset the array from 0 - count($myArray) - 1 and keep the 2nd key intact and its value as well.

Can someone please help me?


$myArray = array_values($myArray);


There might be simpler solutions but here is one working solution:

$myArray = array();
$myArray[32]['value'] = 'value1';
$myArray[32]['type'] = 'type1';
$myArray[33]['value'] = 'value2';
$myArray[33]['type'] = 'type2';
$myArray[35]['value'] = 'value3';
$myArray[42]['value'] = 'value4';
$myArray[42]['type'] = 'type4';

$map = array_flip(array_keys($myArray)); // map old keys to new keys.
$newarray = array();
foreach($myArray as $key => $value) {
    $newarray[$map[$key]] = $value; // use new key and old value.
}


You don't need it. Why not to just leave this array alone? Unnecessary moves would lead your code to a mess.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号