Creating an object from this data
I have the following code which takes the data in a variable $main
and loops through it so that it outputs the markup below
Form1
Firstname
Stack
Lastname
Overflow
Form2
Grade
some grade
Address
some address
School
some school
The code I use to loop through $main
is this, and it outputs markup, as you can see dl,dd,dt, etc. How can I create an object instead that could be traversed as $main_object->form1->firstname
or something like that?
foreach ($main as $info){
foreach ($info as $form => $data){
$output .= '<h4>'. ucfirst($form) .'</h4>';
$output .= '<dl>';
foreach ($data as $key => $value){
$output .= '<dt>'. ucfirst($key) .'</dt>';
if (is_array($value)){
foreach ($value as $label => $val){
$output .= '<dd>'. $val .'</dd>';
开发者_运维百科 }
} else {
$output .= '<dd>'. $value .'</dd>';
}
}
$output .= '</dl>';
}//foreach
}//foreach
Objects can be created by instantiating a new stdClass
instance. You should be able to modify the following example to suit your needs:
$root = new stdClass;
// For each form
$current_form = $root->$form_name = new stdClass;
// For each item
$current_form->$item_name = $item_value;
A dump of the object will then yield something like:
stdClass Object
(
[Form1] => stdClass Object
(
[Firstname] => Stack
// etc..
)
)
Which can then be accessed via:
$root->Form1->Firstname;
精彩评论