Domanda

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 (i.e. brackets etc.) turned into a mess and unserializing just failed.

Thank you in advance.

È stato utile?

Soluzione

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top