I am currently working on a application where I need to parse the data posted into the server. The data is a underscore-delimited string which indicates which parent are they under.
The data posted to the server looks like this:
department: 'Sales'
s1: 'Logistics'
s1_q1_type: multiple
s1_q1: 'Q 1'
s1_q1_c1: ''
s1_q1_c2: ''
s1_q1_c3: ''
s1_q1_correct_c1: 'on'
s1_q1_correct_c2: 'on'
s1_q1_points: 10
s1_q2_type: multiple
s1_q2: 'Q 2'
s1_q2_c1: ''
s1_q2_c2: ''
s1_q2_points: 10
s2: 'Analysis'
s2_q1_type: multiple
s2_q1: 'Q 1'
s2_q1_c1: ''
s2_q1_c2: ''
s2_q1_correct_c2: 'on'
s2_q1_points: 5
s2_q2_type: multiple
s2_q2: 'Q 2'
s2_q2_c1: ''
s2_q2_c2: ''
s2_q2_points: 15
From the code above: s## are "sections", under sections there are q## (questions), then under questions there is: type, points, c## (choices) and correct answer(s). There can be multiple correct answers per question.
I need to parse the above code to an array that looks like this:
department: 'Sales',
sections: {
s1: {
title: 'Logistics',
questions: {
q1: {
title: 'Q 1',
type: multiple,
choices: {
c1: '',
c2: '',
c3: ''
},
correct: {
c1: 'on',
c2: 'on'
},
points: 10
},
q2: {
title: 'Q 2',
type: multiple,
c1: '',
c2: ''
points: 10
}
}
},
s2: {
title: 'Analysis',
questions: {
q1: {
title: 'Q 1',
type: multiple,
choices: {
c1: '',
c2: '',
c3: ''
}
correct: {
c1: 'on'
},
points: 5
},
q2: {
title: 'Q 2'
type: multiple,
c1: '',
c2: ''
points: 15
}
}
}
}
I tried using foreach and checking if weather the key is isset() but then I'm not getting anywhere.
$i = 1;
$array = array();
foreach( $_POST as $key => $value ){
if( isset( $post['s' . $i] ) ){
$array['sections'][$key] = $value;
}
$i++;
}
Any help would be greatly appreciated.