How to retrieve the value stored in a multi-dimensional array and SUM the entries?

I’m trying to retrieve multidimensional values stored in user_meta where the meta key is my_posts and the meta_value is :

a:3:{i:0;s:2:”23″;i:1;s:2:”20″;i:2;s:1:”9″;}

Somewhere in the admin page i want to show the sum of the selected posts which are stored in the value above….

3 Answers
3

The value is serialized, if you retrieve the meta data with the WordPress functions you’ll get that data back unserialized, and you’ll be able to iterate over it(looks like an array).

$somevar = get_user_meta( '99999', 'your-key', true );

As with options in WordPress, user meta is serialized when it’s an array or object, single values get stored as a string(unserialized).

Call get_user_meta and you will get back an array of data back instead of a serialized string, there’s no need for you to serialize and unserialize yourself, the WordPress meta functions take care of this for you, using maybe_serialize and maybe_unserialize when getting and setting meta.

This is similar to option handling in WP and does pretty much the same thing, i covered this when answering “Plugin options table,is the data serialized”..

To answer the question more directly though, to total the values in the array use array_sum, like so..(based on the example var earlier)

if( !empty( $somevar ) )
    $sum = array_sum( $somevar );

Or..

$sum = 0;
if( !empty( $somevar ) ) {
    foreach( $somevar as $int )
        $sum = $sum + $int;
}

Assuming it’s a simple array of key => value pairs either approach should work.

Leave a Comment