2012-07-12 128 views
0

嗨,我从模板中获得以下代码。按字母顺序打印阵列

<ul class="sub-categories"> 
    <?php 

     foreach ($category->getChildren() as $child) { 
      if (!$child->totalItemCount()) continue; 
      $link = $this->app->route->category($child); 
      $item_count = ($this->params->get('template.show_sub_categories_item_count')) ? ' <span>('.$child->totalItemCount().')</span>' : ''; 
      echo '<li><a href="'.$link.'" title="'.$child->name.'">'.$child->name.'</a>'.$item_count.'</li>'; 
     } 

    ?> 
</ul> 

我想子类别的项目(这是由国家划分城市中靠上的代码进行排序。

我想我可能只是排序如下数组$分类 - >的getChildren(),但它没有工作,所以我做了一个回声,它说数组,所以我做了var_dump在该数组上,并得到了一个布尔(真),当我尝试其他方式输出它(print_r)它崩溃的页面

我不太了解数组,所以有人可以解释一下这个数组不是数组吗?我如何排列城市列表?

谢谢!

回答

1

我真的不明白的问题是与要打印的阵列,但我认为定义与usort()这样的自定义排序会是你在找什么:

<?php 

function compareChildren ($a, $b) { 
    return strcmp($a->name, $b->name); 
} 

$children = $category->getChildren(); 
usort($children, 'compareChildren'); 

foreach ($children as $child) { 
    // ... 
} 

这里的一个working example on codepad

+0

这将返回以下错误:致命错误:无法重新声明comparechildren()(之前在... – liz 2012-07-17 21:09:39

+0

中声明,这也是问题的全部要点..为什么print_r和var_dump无法正常工作?正确...他们应该.. – liz 2012-07-17 21:23:43

+0

@liz你是否在一段代码中定义了这个函数,这段代码会运行多次?这将解释你的“之前声明的”错误。 – Wiseguy 2012-07-18 02:31:15