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);