我有多维数组,我得到这样的输出:
Array
(
[Bukit Panjang LRT] => Array
(
[0] => Array
(
[station_name] => Senja (BP13)
)
[1] => Array
(
[station_name] => Ten Mile Junction (BP14)
)
)
[Changi Airport Branch Line (CAL)] => Array
(
[2] => Array
(
[station_name] => Changi Airport (CG2)
)
[3] => Array
(
[station_name] => Expo (CG1 / DT35)
)
)
)
我的foreach循环:
$level_keys = array();
foreach ($mrtlrt_line as $k => $sub_array){
$this_level = $sub_array['header_name'];
$level_keys[$this_level][$k] = array('station_name' => $sub_array['station_name']);
}
我想像这样在HTML元素中显示值:
<h4>Bukit Panjang LRT</h4> <div>
<label class="label_check">
<input name="line" value="1" type="checkbox" />Senja (BP13
</label>
<label class="label_check">
<input name="line" value="2" type="checkbox" />Ten Mile Junction (BP14)
</label> </div>
<h4>Changi Airport Branch Line (CAL)</h4> <div>
<label class="label_check">
<input name="line" value="1" type="checkbox" />Changi Airport (CG2)
</label>
<label class="label_check">
<input name="line" value="2" type="checkbox" />Expo (CG1 / DT35)
</label> </div>
有任何想法或建议吗?感谢。
答案 0 :(得分:2)
试试此代码
<?php
//Your array- `$mrtlrt_line`
foreach($mrtlrt_line as $key => $value)
{
echo '<h4>',$key,'</h4><div>';
foreach($value as $nkey=>$nval)
{
echo '<label class="label_check">';
echo '<input name="line" value="1" type="checkbox" />',$nval;
echo '</label>';
}
echo '</div>';
}
答案 1 :(得分:2)
试试这个
<?php
foreach ($YourMulArr as $key => $subAry)
{
echo "<h4>" . $key . "</h4>";
echo "<div>";
foreach ($subAry as $k => $Ary)
{
echo "<label class='label_check'>";
echo "<input name='line' value='" . $k+1 . "' type='checkbox' /> ". $Ary['station_name'];
echo "</label>";
}
echo "</div>";
}
?>
答案 2 :(得分:0)
您必须从php foreach循环创建html并在其中注入数组值。 看到这段代码
foreach ($mrtlrt_line as $k => $sub_array){
$level_keys[$this_level][$k] = array('station_name' => $sub_array['station_name']);
$level_keys[$this_level][$k+1] = array('station_name' => $sub_array['station_name']);
echo '<h4>'.$sub_array['header_name'].'</h4> <div><label class="label_check"><input name="line" value="1" type="checkbox" />'.$level_keys[$this_level][$k].'</label><label class="label_check"><input name="line" value="2" type="checkbox" />'.$level_keys[$this_level][$k+1].'</label> </div>';
}
我希望你能知道如何将你的数组注入你的html中。
答案 3 :(得分:0)
要扩展swapnesh的答案,你需要2个foreach循环。 Foreach mrtlrt_line你想循环遍历那个数组中的什么。
您应该尽可能地将表示逻辑与业务逻辑分开。这是使用alt php语法的个人选择,但我主观地认为它使演示代码更容易阅读。
<?php foreach($mrtlrt_line as $key => $value): ?>
<?php /* interator */ $i = 0; ?>
<h4><?php echo $key; ?></h4>
<div>
<?php foreach($value as $innerkey=>$innerval): ?>
<label class="label_check">
<input name="line" value="<?php echo $i++; ?>" type="checkbox" />
<?php echo $innernval; ?>
</label>
<?php endforeach; ?>
</div>
<?php endforeach; ?>