我对多维阵列感到困惑。
在下面的db,php和html中,我不明白
的用法foreach ($navlist as $key => $list){
foreach ($list as $topkey => $toplist){..
and
foreach ($toplist['children'] as $subkey => $subname){...
此代码对我来说也很困惑。是['孩子'] php?
$data[0][$row->parentid]['children'][$row->id] = $row->name;
如果您能解释一下这个navgation.php
,我将不胜感激提前致谢。
我在db。中有以下内容。
INSERT INTO `categories` (`id`, `name`, `shortdesc`, `longdesc`, `status`, `parentid`)
VALUES (1, 'shoes', 'Shoes for boys and girls.', '', 'active', 7);
INSERT INTO `categories` (`id`, `name`, `shortdesc`, `longdesc`, `status`, `parentid`)
VALUES (2, 'shirts', 'Shirts and blouses!', '', 'active', 7);
[...]
INSERT INTO `categories` (`id`, `name`, `shortdesc`, `longdesc`, `status`, `parentid`)
VALUES (9, 'test', 'testing', 'Testing!!!!', 'inactive', 0);
模型有以下php
function getCategoriesNav(){
$data = array();
$this->db->select('id,name,parentid');
$this->db->where('status', 'active');
$this->db->orderby('parentid','asc');
$this->db->orderby('name','asc');
$this->db->groupby('parentid,id');
$Q = $this->db->get('categories');
if ($Q->num_rows() > 0){
foreach ($Q->result() as $row){
if ($row->parentid > 0){
$data[0][$row->parentid]['children'][$row->id] = $row->name;
}else{
$data[0][$row->id]['name'] = $row->name;
}
}
}
$Q->free_result();
return $data;
}
和controller / navigation.php
if (count($navlist)){
echo "<ul>";
foreach ($navlist as $key => $list){
foreach ($list as $topkey => $toplist){
echo "<li class='cat'>";
echo anchor("welcome/cat/$topkey",$toplist['name']);
echo "</li>\n";
if (count($toplist['children'])){
foreach ($toplist['children'] as $subkey => $subname){
echo "\n<li class='subcat'>";
echo anchor("welcome/cat/$subkey",$subname);
echo "</li>";
}
}
}
}
echo "</ul>\n";
}
这将产生以下html
<ul>
<li class='cat'>
<a href="http://127.0.0.1/codeigniter_shopping/welcome/cat/7" title="clothes">
clothes
</a>
</li>
<li>
...
</li>
<li class='subcat'>
<a href="http://127.0.0.1/codeigniter_shopping/welcome/cat/5" title="toys">
toys
</a>
</li>
</ul>
答案 0 :(得分:3)
基本结构是:
foreach ($navlist as $key => $list)
这意味着遍历数组$navlist
,并且在$navlist
中每次使用键$key
和值$list
,执行{{1}的正文}循环。
一个更简单的例子可能有所帮助。
foreach
那个的输出(除非我搞砸了),是:
$numbers = array();
$numbers[0] = "Zero";
$numbers[1] = "One";
$numbers[2] = "Two";
foreach($numbers as $number => $text) {
echo $number." is written ".$text."\n";
}
您给出的代码只有多个嵌套循环,因此最外层for循环中的0 is written Zero
1 is written One
2 is written Two
本身就是一个关联数组,然后循环通过,并且存储在该关联数组中的值也是阵列。
您可能会发现阅读foreach
文档具有指导意义。