danyo
danyo

Reputation: 5856

wordpress post_meta update array

I am currently working with wordpress. I needed to be able to save post meta, and update it at a later date without overwriting what was previously stored.

I came up with this quick solution:

    $ref = get_post_meta($post->ID, 'page_ref', true );
update_post_meta($post->ID,'page_ref',array($ref,$newdata));

So basically i am getting the current data, storing it in an array and then adding the $newdata to the array. This works great and is stored in the database like this:

a:2:{i:0;a:2:{i:0;s:0:"";i:1;s:34:"data1";}i:1;s:22:"data2";}

When i then loop through the array like this:

foreach ($ref as $i){

    echo $i;
}

I get the following result:

Arraydata2

I'm not sure if the array is getting stored correctly, and not entirely sure why the returned data is only showing the latest entry to the array?

Any help would be greatly appreciated

Upvotes: 0

Views: 343

Answers (1)

Ravi Patel
Ravi Patel

Reputation: 5231

this is serialized data you can get this data using unserialized method(function)

      $serialized = 'a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}';
        var_dump(unserialize($serialized));

Output:

    Array
    (
        [0] => apple
        [1] => banana
        [2] => orange
    )

<?php echo var_dump(
unserialize('a:2:{i:0;a:2:{i:0;s:0:"";i:1;s:34:"data1";}i:1;s:22:"data2";}')
); ?>
output
bool(false) 

<?php $datas = unserialize(
'a:3:{i:0;s:5:"apple";i:1;s:6:"banana";i:2;s:6:"orange";}'
); 

                    foreach($datas as $key => $val)
                    {
                        echo $val;
                    }



      ?>

Output

applebananaorange 

Upvotes: 2

Related Questions