基本上我以一个JSON格式的字符串开头。此字符串的一个例子是:[{"options":[{"valid":true,"content":"Answer"}],"content":"Question1","type":"text"},{"options":[{"valid":false,"content":"Answer"}],"content":"Question2","type":"radios"}]
随着json_decode
我将它转换成一个数组,看起来像这样在这个例子:通过恢复PHP代码创建JSON字符串
Array
(
[0] => stdClass Object
(
[options] => Array
(
[0] => stdClass Object
(
[valid] => 1
[content] => Answer
)
)
[content] => Question1
[type] => text
)
[1] => stdClass Object
(
[options] => Array
(
[0] => stdClass Object
(
[valid] =>
[content] => Answer
)
)
[content] => Question2
[type] => radios
)
)
并使用该PHP代码存放在MySQL这样的:
$questions = json_decode($_POST['test']);
$con=mysqli_connect("Localhost","root","","test");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
foreach($questions as $question){
$options = $question->options;
$options_id = array();
$question_query = "INSERT INTO `question` (Content, Type) VALUES ('{$question->content}', '{$question->type}')";
echo $question_query;
if(!mysqli_query($con, $question_query)){ echo mysqli_error($con);}
$question_id= mysqli_insert_id($con);
echo $question_id;
foreach($options as $option){
$options_query = "INSERT INTO `option` (Question_id, Content) VALUES ({$question_id}, '{$option->content}')";
echo $options_query;
if(!mysqli_query($con, $options_query)){
echo mysqli_error($con);
}
}
这只是存储问题,这是可能的答案。
因此,在某些时候我需要这个过程向后(从MySQL获取信息并再次构建JSON,以便呈现相应的UI)。有没有一种方法可以恢复这些代码,并使这个过程向后?也许与json_enconde
?
JSON只是一个JavaScript数据结构的字符串表示(一个简单的INT /串,最多的阵列/对象)。你不会“反转”这个过程。你从数据库中汲取数据,建立一个PHP数据结构,然后将THAT编码为json。 –
@MarcB感谢您的解释,我在这个问题上有点困惑。因此,在这种特殊情况下,您认为我可以构建PHP数据结构吗? –
你已经得到了你的var_dump,它显示了你的结构究竟是什么。从那工作。 –