Holden
Holden

Reputation: 1

Make an array of meta user data in WordPress human readable

I have added some data via Gravity Forms to a Wordpress site and I am trying to loop through the data that is stored in the database in an array in a human readable format. The data stored is for MOVIE, ROLE, and YEAR -- here is how the data is stored in the database:

s:298:"a:3:{i:0;a:3:{s:4:"Year";s:4:"2010";s:5:"Movie";s:18:"Mission Impossible";s:4:"Role";s:5:"Actor";}i:1;a:3:{s:4:"Year";s:4:"2011";s:5:"Movie";s:20:"Mission Impossible 2";s:4:"Role";s:10:"Lead Actor";}i:2;a:3:{s:4:"Year";s:4:"2012";s:5:"Movie";s:20:"Mission Impossible 3";s:4:"Role";s:8:"Director";}}";

Any ideas on how to loop through that and output the data in a human readable way will be most appreciated... I will paypal a beer to anyone that can help...

Thanks in advance!

Upvotes: 0

Views: 641

Answers (2)

MrCode
MrCode

Reputation: 64526

$data = 's:298:"a:3:{i:0;a:3:{s:4:"Year";s:4:"2010";s:5:"Movie";s:18:"Mission Impossible";s:4:"Role";s:5:"Actor";}i:1;a:3:{s:4:"Year";s:4:"2011";s:5:"Movie";s:20:"Mission Impossible 2";s:4:"Role";s:10:"Lead Actor";}i:2;a:3:{s:4:"Year";s:4:"2012";s:5:"Movie";s:20:"Mission Impossible 3";s:4:"Role";s:8:"Director";}}";';

// first remove the string declaration at the start, if you don't do this, unserialize() will treat most of the data as a string and won't convert it to an array
$data = substr($data, strpos($data, '"')+1);

// now just unserialize into an array so it can be looped through with foreach() etc
$arr = unserialize($data);

print_r($arr);

Outputs

Array
(
    [0] => Array
        (
            [Year] => 2010
            [Movie] => Mission Impossible
            [Role] => Actor
        )

    [1] => Array
        (
            [Year] => 2011
            [Movie] => Mission Impossible 2
            [Role] => Lead Actor
        )

    [2] => Array
       (
            [Year] => 2012
            [Movie] => Mission Impossible 3
            [Role] => Director
        )

)

To loop through an array you can use foreach:

<?php

$html = '<table>';

// table headings
$html .= '<tr><th>Year</th><th>Movie</th><th>Role</th></tr>';

foreach($arr as $item)
{
    $html .= '<tr>';
    $html .= '<td>' . $item['Year'] . '</td>';
    $html .= '<td>' . $item['Movie'] . '</td>';
    $html .= '<td>' . $item['Role'] . '</td>';
    $html .= '</tr>';
}

 $html .= '</table>';

echo $html; // output the HTML table
?>

Upvotes: 1

zuzuleinen
zuzuleinen

Reputation: 2634

Have you tried to unserialize this string?

Upvotes: 1

Related Questions