0

i need to unserialize a string to an array.Here is the stringwhich needs to be unserialized in php to assosiative array.

a:1:{i:0;s:158:"a:6:{s:5:"rowid";s:32:"94ca9ee0c4e3184b50e89e82f80332fb";s:2:"id";
s:2:"68";s:3:"qty";s:1:"1";s:5:"price";
s:2:"20";s:4:"name";
s:5:"Bread";s:8:"subtotal";i:20;}";

}

1 Answer 1

3

It looks like this has been doubly serialized. It expands to an array with a single element, and that element is a serialized associative array. So you need to do:

$temp = unserialize($data);
$result = unserialize($temp[0]);
var_dump($result);

Result:

array(6) {
  ["rowid"]=>
  string(32) "94ca9ee0c4e3184b50e89e82f80332fb"
  ["id"]=>
  string(2) "68"
  ["qty"]=>
  string(1) "1"
  ["price"]=>
  string(2) "20"
  ["name"]=>
  string(5) "Bread"
  ["subtotal"]=>
  int(20)
}

If there can be more that one element in the top-level serialized array, use array_map to unserialize all of them:

$result = array_map('unserialize', $temp);

$result will now be a 2-dimensional array.

I'm not sure why you stored your data this way. Why not just serialize the original 2-d array all at once, instead of nesting them?

Sign up to request clarification or add additional context in comments.

2 Comments

its working fine, but how could we foreach this array to get the values
thanx it worked fine, the string is returned from an api call.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.