-1

Possible Duplicate:
How should I sort this array by key with usort?

I have tried following a lot of hints to sort a list alphabetically on this piece of code with no luck.

<?php
foreach ($this->link_items as &$item) :
?>
<li>
<a href="<?php echo JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catid)); ?>">
            <?php echo $item->title; ?></a>
</li>
<?php endforeach; ?>

I need this list to be sortet before its output.

Community
  • 1
  • 1

2 Answers2

0
sort($this->link_items);

This will sort values by their value. To sort by key, use ksort.

Connor Deckers
  • 2,447
  • 4
  • 26
  • 45
  • the `$link_items` are objects, so this wont work. The OP needs to use `usort` and compare the item titles. – Gordon Jun 16 '12 at 07:55
  • He doesn't actually mention this in his question. I worked with the information he provided. Does this really require a downvote? – Connor Deckers Jun 16 '12 at 07:58
  • It's fairly obvious from the question given that the OP first does `foreach ($this->link_items as &$item)` and then accesses `$item->title` and other properties. As for the dv, well, technically the answer is wrong, so yes, but it's more meant to encourage you to correct the question (not to punish you). – Gordon Jun 16 '12 at 08:00
  • An array can be read in an object oriented method, as he has here. There is nothing saying it can't be an array he is sorting. – Connor Deckers Jun 16 '12 at 08:01
  • Occam's Razor: the most obvious explanation for two competing theories is usually the right explanation and `$item->title` hints at an object property. Besides, if the OP doesnt know how to sort a list of objects by their properties, s/he likely wont know how to use an ArrayObject (not an array) either. – Gordon Jun 16 '12 at 08:02
  • Agree. But, just because somethings obvious, doesn't make it the truth. I've seen more obscure usages of arrays before. But, I see your point. – Connor Deckers Jun 16 '12 at 08:07
-1

USE:

$sorted_array = array_multisort($this->link_items, SORT_ASC);
<?php
foreach ($sorted_array as &$item) :
?>
<li>
<a href="<?php echo JRoute::_(ContentHelperRoute::getArticleRoute($item->slug, $item->catid)); ?>">
            <?php echo $item->title; ?></a>
</li>
<?php endforeach; ?>
  • `array_multisort` returns a boolean. even if it would return the sorted array, the result will likely be wrong because the objects have multiple properties. – Gordon Jun 16 '12 at 08:08