2012-07-12 105 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