Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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....

share|improve this question
    
if by sum you mean amount then you can use echo count(unserialize('a:3:{i:0;s:2:"23";i:1;s:2:"20";i:2;s:1:"9";} ')); –  Bainternet Feb 18 '11 at 12:03

3 Answers 3

PHP solution:

$tmp = 'a:3:{i:0;s:2:"23";i:1;s:2:"20";i:2;s:1:"9";}';
echo sum_array(unserialize($tmp));
share|improve this answer
    
There's no need to do unserialization with user meta, it's only serialized because the meta data is an array or object(see my answer, which will be posted in just a sec). –  t31os Feb 18 '11 at 12:02
    
Ok thanks. I didn't know user_meta was unserialized on the fly since I've never had to use it for now ;) –  Kaaviar Feb 18 '11 at 12:39
    
I wasn't sure initially, so i checked the source, handy to know WordPress does serialization on user meta to.. :) –  t31os Feb 18 '11 at 18:35

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.

share|improve this answer

Also...cast your meta value as an array and look at the wp_count_posts() and how it's used in wp-admin/edit-form-advanced.php for an example.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.