tags:

views:

52

answers:

3

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

A: 

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.
}
codaddict
A: 

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

Col. Shrapnel
because the 1st key index is linked to an id that I don't want others to be able to have access to for security reasons!
SoLoGHoST
@sologhost who forces you to print keys out? Ever tried to think before doing?
Col. Shrapnel
HA HA, well sure, I have tried this, I'm just tired from thinking so much already that I'm experiencing Brain Farts...lol
SoLoGHoST
And furthermore, I need to get the id as the first key so that it can be sorted by id value using ksort(). IT MUST BE SORTED. But after sorting it, I am returning it into an array that others will have access to. So it needs to be 0 indexed.
SoLoGHoST
@sologhost Users don't have access to your arrays.
Col. Shrapnel
+1  A: 
$myArray = array_values($myArray);
Jakub Kulhan
+1 good one :)..
codaddict
Thanks this works, didn't know that using array_values would keep the 2nd key index intact as well.CHEERS :)
SoLoGHoST