多维数组中的php iconv键

时间:2022-05-02 01:34:17

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

在多维数组中有没有合适的iconv键?

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.

我需要json_encode一个,但首先它必须是unicode,对吗?那么,有什么黑客或其他什么?在一些简单的attemts(array_walk_recursive?)后,我尝试序列化完整的数组,然后iconv,然后反序列化 - 但是所有标点符号(即括号等)变成了一个混乱,并且反序列化只是失败了。

Thank you in advance.

先感谢您。

1 个解决方案

#1


0  

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

在常见情况下,使用array_walk_recursive()无法实现这一点 - 因为它不适用于那些键,这些值是数组:

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.

- 我建议阅读iconv手册页以了解转换修饰符。

#1


0  

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

在常见情况下,使用array_walk_recursive()无法实现这一点 - 因为它不适用于那些键,这些值是数组:

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.

- 我建议阅读iconv手册页以了解转换修饰符。