Reputation: 53
Array cannot get value by key from unserialize. It show error Undefined offset, but the array has the index call "1134". How can I get the index 1134 value?
$original = unserialize('O:8:"stdClass":1:{s:4:"1134";i:1;}');
$result = (array)$original;
print_r ($result); //Array ( [1134] => 1 )
print_r($result["1134"]); //Undefined offset: 1134
print_r($result['1134']); //Undefined offset: 1134
print_r($result[1134]); //Undefined offset: 1134
Upvotes: 3
Views: 905
Reputation: 31
Your code is running fine in my PHP version 7.2. It seems you are using PHP 5.4 or 5.6. Anyway I have updated code for your php version and hope it will work.
$original = unserialize('O:8:"stdClass":1:{s:4:"1134";i:1;}');
$result = json_decode(json_encode($original), True);
print_r ($result);
print_r($result["1134"]);
print_r($result['1134']);
print_r($result[1134]);
Upvotes: 2
Reputation: 743
You've to iterate over your unserialized data and then store it into an array:
<?php
$original = unserialize('O:8:"stdClass":1:{s:4:"1134";i:1;}');
$arr = [];
foreach($original as $key => $values) {
$arr[$key] = $values;
}
echo $arr[1134] // outputs 1
?>
Output:-https://3v4l.org/B94OS#v5638
Upvotes: 2
Reputation: 9693
Try this, you can use it like object or may like to use get_object_vars() to use it like array or may use type casting.
<?php
$original = unserialize('O:8:"stdClass":1:{s:4:"1134";i:1;}');
var_dump($original->{1134}); //Object
var_dump(get_object_vars($original)['1134']); //array
?>
Upvotes: 2
Reputation: 251
$original = unserialize('O:8:"stdClass":1:{s:4:"1134";i:1;}');
$result = (array)$original;
print_r($result[1134]); //print 1
Upvotes: 1