我有一个如下所示的数组,并希望从中创建一个<html>
表单。我试图做到这一点,但我似乎无法弄清楚如何循环内部/嵌套数组,它具有我想要使用的值。
任何人都可以帮助我吗?为了清楚起见,我想要一个html输出,如:
<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>
功能
<?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
(
[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
)
)
)
)
)
答案 0 :(得分:1)
您根本没有考虑数据结构。
foreach ($item as $value =>$data) {
$toreturn .='<option value="'.$value['props']['options'].'">'.$value['props']['options'].'</option>';
}
在此,$item
是
[props] => Array
(
[required] => 0
[label] => I have
[tip] =>
[options] => Array
因此,遍历它将循环遍历属性,而不是值。你想循环$item['options']
。
总而言之,如果你没有使用数组(PHP的基础和必要类型),我建议你在尝试这样的事情之前回去做一些初学者材料。