How do I get serialize data on wordpress

How do I get serialize data on wordpress database?

Example

Read More
option_name               option_value
-----------------------------------------------------------
widget_example-widget     a:3:{i:2;a:0:{}i:6;a:4:{s:5:"title";s:14:"Example Widget";s:4:"name";s:8:"John Doe";s:3:"age";s:2:"30";s:3:"sex";s:4:"male";}s:12:"_multiwidget";i:1;}

Example I want to call sex and I use

$sex = get_option('widget_example-widget');
echo $sex['sex'];

It return empty and when try var_dump result like below

array(3) {
  [2]=>
  array(0) {
  }
  [6]=>
  array(4) {
    ["title"]=>
    string(14) "Example Widget"
    ["name"]=>
    string(8) "John Doe"
    ["age"]=>
    string(2) "30"
    ["sex"]=>
    string(4) "male"
  }
  ["_multiwidget"]=>
  int(1)
}

Actually I can retrieve this data by add $sex['6']['sex'] but the problem here the [6]=> is dynamic. When we activate/deactivate the widget it can be in another value.

Question

How do I get a correct data for this one?

Related posts

Leave a Reply

2 comments

  1. I’m not sure of what you really want, but maybe try a function that check every array to see if “sex” index isset, and return the value if it is. Not very efficient but it should do it anyway…

  2. $data = 'a:2:{i:0;s:12:"Sample array";i:1;a:2:{i:0;s:5:"Apple";i:1;s:6:"Orange";}}';
    
    $unserialized = unserialize($data);
    
    print_r($unserialized);
    

    Result:

    Array
    (
        [0] => Sample array
        [1] => Array
            (
                [0] => Apple
                [1] => Orange
            )
    )