下面是我的数据库值,我想使用php检索answer_id。
a:1:{i:0;O:8:'"stdClass'":7:{s:11:'"question_id'";s:1:'"1'";s:13:'"question_text'";s:18:'"This is question 1'";s:9:'"answerswer_id'";s:1:'"2'";s:11:'"answerswer_text'";s:4:'"asss'";s:11:'"points_base'";s:1:'"2'";s:6:'"points'";s:1:'"2'";s:15:'"custom_response'";s:0:'"'";}}
尝试下面的代码,它会向您返回答案id。
$str = "a:1:{i:0;O:8:'"stdClass'":7:{s:11:'"question_id'";s:1:'"1'";s:13:'"question_text'";s:18:'"This is question 1'";s:9:'"answerswer_id'";s:1:'"2'";s:11:'"answerswer_text'";s:4:'"asss'";s:11:'"points_base'";s:1:'"2'";s:6:'"points'";s:1:'"2'";s:15:'"custom_response'";s:0:'"'";}}";
$arry = unserialize($str);
echo $arry[0]->answer_id;
问题是您的序列化字符串包含反斜杠,这会扰乱序列化对象。解决方案:删除反斜杠并取消字符串的序列化,你就会得到你的对象:
<?php
$strSerializedWithSlashes = 'a:1:{i:0;O:8:'"stdClass'":7:{s:11:'"question_id'";s:1:'"1'";s:13:'"question_text'";s:18:'"This is question 1'";s:9:'"answerswer_id'";s:1:'"2'";s:11:'"answerswer_text'";s:4:'"asss'";s:11:'"points_base'";s:1:'"2'";s:6:'"points'";s:1:'"2'";s:15:'"custom_response'";s:0:'"'";}}';
$strSerializedWithoutSlashes = str_replace("''", "", $strSerializedWithSlashes);
$objUnSerialized = unserialize($strSerializedWithoutSlashes);
var_dump($objUnSerialized);
// DUMPS::
array (size=1)
0 =>
object(stdClass)[1]
public 'question_id' => string '1' (length=1)
public 'question_text' => string 'This is question 1' (length=18)
public 'answer_id' => string '2' (length=1)
public 'answer_text' => string 'asss' (length=4)
public 'points_base' => string '2' (length=1)
public 'points' => string '2' (length=1)
public 'custom_response' => string '' (length=0)
您可以在此处进行测试:https://eval.in/571535
现在;让你回答id你可以简单地这样做:
<?php
$objData = $objUnSerialized[0];
$answerID = $objData->answer_id;
var_dump($answerID); // DUMPS: '2'