Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing character encoding of multidimensional array

Tags:

php

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, because I have to use json_encode and json_decode on them, I need to store at least the stuff in data as UTF-8. Unfortunately, the website uses windows-1252, and that's something I can't change. Because I might want to add even more levels to the array (within data) in the future, I figured I'd change the encoding recursively, like so:

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 is not working. If I print $arr[$n] right after encoding it, it comes out right, but the original array doesn't seem to change, because when I later try to print out the values from the array, I get character encoding issues.

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

How can I make it so that the original array is changed?

EDIT: Thanks to a helpful commenter, I now know what I was doing wrong. I forgot to actually return the array after doing the encoding. Here's 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);
like image 525
Tommy Brunn Avatar asked Feb 01 '12 13:02

Tommy Brunn


1 Answers

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 one-liner:

array_walk_recursive($ourThing, function(&$item) { $item = mb_convert_encoding($item, 'Windows-1252', 'UTF-8'); });
like image 185
Travesty3 Avatar answered Sep 18 '22 13:09

Travesty3