views:

208

answers:

4

I am reading in a bunch of multi-dimensional arrays, and while digging through them I have noticed that some of the keys are incorrect.

For each incorrect key, I simply want to change it to zero:

from:

$array['bad_value']

to:

$array[0]

I want to retain the value of the array element, I just want to change what that individual key is. Suggestions appreciated.

Cheers

+1  A: 

Bruteforce method:

$array[0] = $array['bad_value'];
unset($array['bad_value']);
thephpdeveloper
yeah but since this array is part of a multidimensional array I need to maintain its position in its containing array
Evernoob
you can't maintain the position while changing the key - can you?
thephpdeveloper
not unless the position is numeric, which it is.
Evernoob
nope. Even when numeric, the position might not be in order. Read up documentation on PHP Arrays and Internal Pointers. You can sort around the array, but the keys remain.
thephpdeveloper
+5  A: 

if you change multiple keys to 0 you will overwrite the values...

you could do it this way

$badKey = 'bad_value';
$array[0] = $array[$badKey];
unset($array[$badKey]);
Nicky De Maeyer
A: 
$array['0'][] = $array['bad_value'];
unset( $array['bad_value'] );

Then it will be an array in $array['0'] with values of broken elements.

silent
A: 

Well seeing as you said the keys can be changed to any numeric value how about this?

$bad_keys = array('bad_key_1', 'bad_key_2' ...);
$i = 0;
foreach($bad_keys as $bad_key) {
    $array[$i] = $array[$bad_key];
    unset($array[$bad_key]);
    $i++;
}

EDIT: The solution I gave was horrible and didn't really solve the problem as there are multiple bad keys, this should be better.

RMcLeod
That's awful. There's absolutely no need to loop on the entire array. PHP perfectly knows how to get a named array element without looping the whole of it.
Damien MATHIEU