Changing the character encoding of a multidimensional array

I have a multidimensional array that looks something like this:

ourThing = array( 'id' => 1, 'title' => 'foo', 'data' => array( 'name' => 'bar', 'metadata' => array( 'time' => '2011-02-01 12:00:00' ) ) ); 

Now, since I have to use json_encode and json_decode for them, I need to save at least the stuff in data as UTF-8. Unfortunately, the site uses windows-1252, and I can’t change anything. Since in the future I will want to add even more levels to the array (within the data), I decided that I would recursively change the encoding:

 function encode_items($arr) { foreach ($arr as $n => $v) { if (is_array($v)) encode_items($arr[$n]); else $arr[$n] = mb_convert_encoding($v, 'Windows-1252', 'UTF-8'); } } 

However, this does not work. If I print $ arr [$ n] right after it is encoded, this will work correctly, but the original array does not seem to change, because when I try to print the values ​​from the array later, I get problems with character encoding.

tl; dr: I need to change the encoding of information in ourThing['data'] from utf-8 to windows-1252.

How can I make the original array be modified?

EDIT: Thanks to the helpful commentator, I now know what I'm doing wrong. I forgot to return the array after encoding. Here is a working example:

 ourArray = array( 'id' => 1, 'title' => 'foo', 'data' => array( 'name' => 'bar', 'metadata' => array( 'time' => '2011-02-01 12:00:00' ) ) ); function encode_items($arr) { foreach ($arr as $n => $v) { if (is_array($v)) { $arr[$n] = encode_items($v); } else { $arr[$n] = mb_convert_encoding($v, 'Windows-1252', 'UTF-8'); } } return $arr; } $ourArray = encode_items($ourArray); 
+7
source share
2 answers

:-)

 function encode_items($array) { foreach($array as $key => $value) { if(is_array($value)) { $array[$key] = encode_items($value); } else { $array[$key] = mb_convert_encoding($value, 'Windows-1252', 'UTF-8'); } } return $array; } 

Or you can pass the array by reference, but I prefer this.

+7
source

How about this:

 function myEncodeFunction(&$item) { $item = mb_convert_encoding($item, 'Windows-1252', 'UTF-8'); } array_walk_recursive($ourThing, 'myEncodeFunction'); 

Or even turn it into a single line:

 array_walk_recursive($ourThing, function(&$item) { $item = mb_convert_encoding($item, 'Windows-1252', 'UTF-8'); }); 
+11
source

All Articles