WordPress: get data from array in database

I have custom fields that are created dynamicaly. I get the data from those fields and store it into a database as an array with update_post_meta. It’s stored as a serialised array in the database:

a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}

Now I need to get this array and echo it out on the website, so it looks something like: 4 children (1993,1994,1995,1996).

Read More

Here’s the code I use now, but it doesn’t work.

<?php
$children = get_post_custom_values('rbchildyear');

foreach ($children as $key => $value){
  echo "$key => $value('rbchildyear')<br>";
}
?>

And thats what I get in the front office:

0 => a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}('rbchildyear')

So how can I do that?

Thank you!

Related posts

Leave a Reply

2 comments

  1. use unserialize().

    $children = unserialize('a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";}');
    
    print_r($children);
    

    This will return array

  2. If you use get_post_meta it will return an array of values (numerically indexed). Then you can loop through the array with a foreach.

    $childYears = get_post_meta($post_id, "rbchildyear", true);
    
    foreach($childYears AS $theYear)
    {
         $printThis .= $theYear.",";
    }
    
    print count($childYears)." children ( ".$printThis." )";