DanCake
DanCake

Reputation: 2003

Best way to unserialize within an array

I have an array which contains serialized data similar to the example below.

Array
(
    [0] => Array
        (
            [id] => 4
            [data] => a:2:{s:6:"Series";a:1:{s:11:"description";s:11:"hello world";}s:4:"Type";a:1:{i:0;s:1:"1";}}
            [created] => 2009-10-12 18:45:35
        )
    [1] => Array
        (
            [id] => 3
            [data] => a:2:{s:6:"Series";a:1:{s:11:"description";s:11:"hello world";}s:4:"Type";a:1:{i:0;s:1:"1";}}
            [created] => 2009-10-12 17:39:41

        )
    ...
)

What would be the best way to unserialize the value of the data key and replace the serialized data with its contents?

I have tried looping using a reference which works although the last two entries in the array are identical when they shouldn't be.

foreach($data as &$item) {
    $item['data'] = unserialize($item['data']);
}

Upvotes: 0

Views: 4581

Answers (3)

swordofpain
swordofpain

Reputation: 149

Something like that will work :

$data2 = array ();
foreach($data as $item) {
    $item['data'] = unserialize($item['data']);
    $data2[] = $item;
}

If you want not to use another array :

foreach($data as $k => $item) {
    $data[$k]['data'] = unserialize($item['data']);
}

Upvotes: 0

Gumbo
Gumbo

Reputation: 655189

Yet another way:

foreach ($data as $key => $item) {
    $data[$key]['data'] = unserialize($item['data']);
}

Or:

foreach ($data as $item) {
    $item['data'] = unserialize($item['data']);
    $data[] = $item;
}
$data = array_slice($data, count($data)/2);

Upvotes: 1

Stefan Gehrig
Stefan Gehrig

Reputation: 83622

Using references in a foreach-loop can introduce hard-to-track and mysterious behaviours. You should use a simple for-loop instead.

$num = count($data);
for ($i = 0; $i < $num; $i++)
{
    $item[$i]['data'] = unserialize($item[$i]['data']);
}

Upvotes: 3

Related Questions