Get Data from Serialized Array in PHP

I have a plugin that posts serialized data. Now using unserialize the final output I get for the array is this

array(1) { [0]=> array(2) { ["site_id"]=> int(1) ["posts"]=> array(3) { [8]=> int(121) [9]=> int(164) [10]=> int(163) } } }

Now I want to get the data which is in the last array ie array (3) which means there are 3 records inside this eg showing 8 => init (121)

What I want is the 3 numbers in the arrary 121, 164 and 163.

If the records are 4 then the generated record is like this
array(1) { [0]=> array(2) { ["site_id"]=> int(1) ["posts"]=> array(4) { [8]=> int(121) [9]=> int(164) [10]=> int(163) [11]=> int(189) } } }

Is there any way I can retrieve these? I searched a lot but unable to get a code to retrieve this specific data.

Have a look at https://repl.it/CmX2 for an idea of how this work.
Feel free to ask any questions if you have them :slight_smile:

1 Like

Amazing!!! Thanks a ton! Works exactly as required.

Cool. Do you understand why?
As an extra exercise to get familiar with this, how would you get the value 10 from the following array?

$data = array (
  'data' => 
  array (
    'foo' => 'bar',
    'baz' => 
    array (
      0 => 
      array (
        'ban' => 
        array (
          'bar' => 10,
        ),
      ),
    ),
  ),
);
1 Like

Ok I am not sure if my code is right but based on the code you had added here is how I got the value 10

  'data' => 
  array (
    'foo' => 'bar',
    'baz' => 
    array (
      0 => 
      array (
        'ban' => 
        array (
          'bar' => 10,
        ),
      ),
    ),
  ),
);
$data2 = ( $data['data']['baz']);
foreach ($data2[0]['ban'] as $key => $value) {
	echo 'Key ', $key, ' has value ', $value, "\n";
}```

Let me know if I did it right or if there is a better solution.

Thanks once again.

I personally would not have used a $data2 but just use $data[‘data’][‘baz’][0][‘ban’] directly.
But other than that you got the general gist of it, yes :slight_smile:

Yup thanks for the help. Got a better idea today of how to work with such arrays.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.