简体   繁体   中英

php iconv keys in multidimensional array

Is there any decent way to iconv keys in a multidimensional array?

I need to json_encode one, but first it has to be in unicode, right? So, is there any hack or something? After some straightforward attemts (array_walk_recursive?) I've tried serializing the full array, then iconv, then unserializing - however all punctuation (ie brackets etc.) turned into a mess and unserializing just failed.

Thank you in advance.

You can not achieve that with array_walk_recursive() in common case - since it will not work with those keys, which values are arrays :

Any key that holds an array will not be passed to the function.

Instead of this you can write simple manual walk through:

function iconvKeys(array &$rgData, $sIn, $sOut)
{
   $rgData = array_combine(array_map(function($sKey) use ($sIn, $sOut)
   {
      return iconv($sIn, $sOut, $sKey);
   }, array_keys($rgData)), array_values($rgData));
   foreach($rgData as &$mValue)
   {
      if(is_array($mValue))
      {
         $mValue = iconvKeys($mValue, $sIn, $sOut);
      }
   }
   return $rgData;
}

$rgData = iconvKeys($rgData, 'UCS-2', 'UTF-8');//sample

-I suggest also to read iconv manual page to be aware about conversion modifiers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM