基本上我是从一个JSON格式的字符串开始的。此字符串的一个示例是:[{"options":[{"valid":true,"content":"Answer"}],"content":"Question1","type":"text"},{"options":[{"valid":false,"content":"Answer"}],"content":"Question2","type":"radios"}]
使用json_decode
我将其转换为此示例中的数组:
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
?
答案 0 :(得分:1)
你看起来像下面
$a = '[{"options":[{"valid":true,"content":"Answer"}],"content":"Question1","type":"text"},{"options":[{"valid":false,"content":"Answer"}],"content":"Question2","type":"radios"}]' ;
$b = json_decode($a,true);
//print_r($b);
foreach($b as $key=>$val){
echo 'Content : '.$val['content'];
echo '<br />';
echo 'Type : '.$val['type'];
echo '<br />';
foreach($val['options'] as $key1=>$val1){
echo 'Valid :'.$val1['valid'];
echo '<br />';
echo 'Answer : '.$val1['content'];
echo '<br />';
}
echo '<hr><br />';
}
输出看起来像
Content : Question1
Type : text
Valid :1
Answer : Answer
------------------------------------------------------
Content : Question2
Type : radios
Valid :
Answer : Answer