I have the following PHP array:
$data = array(
'data' => array(
'first_key' => 'first_value',
'second_key' => 'second_value',
'third_key' => 'third_value',
'fourth_key' => array(
'mini_first' => 'mini_value'
)
)
);
I need to apply filters to the keys and values. For simplicity's sake, I need to convert to uppercase and add another character:
$data = array(
'DATA' => array(
'FIRST_KEYx' => 'FIRST_VALUEx',
'SECOND_KEYx' => 'SECOND_VALUEx',
'THIRD_KEYx' => 'THIRD_VALUEx',
'FOURTH_KEYx' => array(
'MINI_FIRSTx' => 'MINI_VALUEx'
)
)
);
Suppose you don't know how many array levels the array will have. How can I solve this?
I think this is right:
<?php
$data = array(
'data' => array(
'first_key' => 'first_value',
'second_key' => 'second_value',
'third_key' => 'third_value',
'fourth_key' => array(
'mini_first' => 'mini_value'
)));
function convert($array){
$new = array();
foreach($array as $key => $value){
if(is_array($value)){
$new[strtoupper($key)."x"] = convert($value);
}else{
$new[strtoupper($key)."x"] = strtoupper($value)."x";
}
}
return $new;
}
print_r(convert($data));