我正在使用http://www.bootply.com/nZaxpxfiXz作为下拉列表。 但我的数据集就像
grep -A 10 -B 10 "ABC" myfile.txt
我想构建一个包含类别和子类别的下拉列表。 哪个有parent_id,那些将是一个类别的子类别。
如何使我的php数组适合这个视图?
array(
(int) 0 => array(
'Genre' => array(
'id' => '1',
'name' => 'Alternative Rock',
'is_active' => true,
'updated' => '2015-10-03 19:19:39',
'parent_id' => '24'
)
),
(int) 1 => array(
'Genre' => array(
'id' => '2',
'name' => 'College Rock',
'is_active' => true,
'updated' => '2015-10-03 19:19:45',
'parent_id' => '24'
)
),
(int) 2 => array(
'Genre' => array(
'id' => '3',
'name' => 'Experimental Rock',
'is_active' => true,
'updated' => '2015-10-03 19:19:50',
'parent_id' => '24'
)
),
(int) 3 => array(
'Genre' => array(
'id' => '4',
'name' => 'Goth Rock',
'is_active' => true,
'updated' => '2015-10-03 19:19:57',
'parent_id' => '24'
)
),
(int) 4 => array(
'Genre' => array(
'id' => '5',
'name' => 'Grunge',
'is_active' => true,
'updated' => '2015-01-29 17:16:15',
'parent_id' => null
)
),
(int) 5 => array(
'Genre' => array(
'id' => '6',
'name' => 'Hardcore Punk',
'is_active' => true,
'updated' => '2015-01-29 17:16:15',
'parent_id' => null
)
),
(int) 6 => array(
'Genre' => array(
'id' => '7',
'name' => 'Hard Rock',
'is_active' => true,
'updated' => '2015-01-29 17:16:15',
'parent_id' => null
)
),
(int) 7 => array(
'Genre' => array(
'id' => '10',
'name' => 'Pop',
'is_active' => true,
'updated' => '2015-10-03 16:38:43',
'parent_id' => null
)
),
(int) 8 => array(
'Genre' => array(
'id' => '24',
'name' => 'Rock',
'is_active' => true,
'updated' => '2015-10-03 19:19:32',
'parent_id' => null
)
)
)
答案 0 :(得分:1)
这应该这样做。但是您可能需要重新考虑放置getChildren函数的位置(为简单起见,我将其包含在内联中),您可能希望创建一个CakePHP视图助手类,甚至在进入视图之前在控制器中执行该逻辑。
<li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown <b class="caret"></b></a>
<ul class="dropdown-menu">
<?php foreach ($genres as $genre) : ?>
<?php if ($genre['Genre']['parent_id'] == null) : ?>
<?php $children = getChildren($genres, $genre['Genre']['id']); ?>
<li class="<?php echo empty($children) ? '' : 'dropdown dropdown-submenu'; ?>">
<?php $a_string = 'class="dropdown-toggle" data-toggle="dropdown"'; ?>
<a href="#" <?php echo empty($children) ? '' : $a_string; ?>>
<?php echo $genre['Genre']['name']; ?>
</a>
<?php if (!empty($children)) : ?>
<ul class="dropdown-menu">
<?php foreach ($children as $child) : ?>
<li><a href="#"><?php echo $child['Genre']['name']; ?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endif; ?>
<?php endforeach; ?>
</ul>
</li>
<?php
function getChildren($genres, $parent_id) {
$children = array();
foreach ($genres as $genre_inner) {
if ($genre_inner['Genre']['parent_id'] == $parent_id) {
$children[] = $genre_inner;
}
}
return $children;
}
?>