Reputation: 405
I have an array like below and would like to create a <html>
form out of it. I tried to accomplish that but I can't seem to figure out how to loop through the inner/nested array, that have the values that i want to use.
Can anyone help me out? Just to be clear, I would like a html output like:
<form method="get">
<h2>I have</h2>
<input type="checkbox" value="own studio">own studio<br>
<input type="checkbox" value="mobile studio">mobile studio<br>
<input type="checkbox" value="makeup artist">makeup artist<br>
<h2>Customers</h2>
<select>
<option value="Private">Private</option>
<option value="Business">Business</option>
</select>
</form>
Function
<?php
function get_listing_cfs() {
global $wpdb;
$serialized=$wpdb->get_var("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key='va_form'");
$array=unserialize($serialized);
$source = array_filter($array, function($el) {
return !(
$el['props']['label'] == 'Exclude' ||
$el['props']['label'] == 'Exclude 2'
);
});
//echo '<pre>'.print_r($source, true).'</pre>';
$toreturn = '<form method="get">';
foreach ($source as $key => $item) {
$toreturn .= '<h2>'.$source[$key]['props']['label'].'</h2>';
if ($source[$key]['type'] == 'select'){
$toreturn .= '<select>';
// Scan through inner loop
foreach ($item as $value =>$data) {
$toreturn .='<option value="'.$value['props']['options'].'">'.$value['props']['options'].'</option>';
}
$toreturn .='</select>';
}
if ($source[$key]['type'] == 'checkbox'){
// Scan through inner loop
foreach ($item as $value =>$data) {
$toreturn .='<input type="checkbox" value="'.$value['props']['options'].'">'.$value['props']['options'].'<br />';
}
}
}
$toreturn .= '</form>';
return $toreturn;
}
?>
Array
Array
(
[0] => Array
(
[id] => app_i_have
[type] => checkbox
[props] => Array
(
[required] => 0
[label] => I have
[tip] =>
[options] => Array
(
[0] => Array
(
[baseline] => 0
[value] => mobile studio
)
[1] => Array
(
[baseline] => 0
[value] => own studio
)
[2] => Array
(
[baseline] => 0
[value] => makeup artist
)
)
)
)
[1] => Array
(
[id] => app_customers
[type] => select
[props] => Array
(
[required] => 0
[label] => Customers
[tip] =>
[options] => Array
(
[0] => Array
(
[baseline] => 0
[value] => Private
)
[1] => Array
(
[baseline] => 0
[value] => Business
)
)
)
)
)
Upvotes: 0
Views: 101
Reputation: 3156
You're not considering your data structure at all.
foreach ($item as $value =>$data) {
$toreturn .='<option value="'.$value['props']['options'].'">'.$value['props']['options'].'</option>';
}
In this, $item
is
[props] => Array
(
[required] => 0
[label] => I have
[tip] =>
[options] => Array
So looping through it would be looping through the properties, not the values. You want to loop $item['options']
.
Over all, if you're not experienced with array (a base and necessary type in PHP), I suggest you go back and do some starter material before trying something like this.
Upvotes: 1