views:

26

answers:

2

Its my array:

$hello = Array(
[text] => Array([name] => blabla [num] => 10)
[sometext] => Array([name] => blabla [num] => 2)
[anytext] => Array([name] => blabla [num] => 1)
)

How to sort this array by [num]?

Should look like (on echo):

<ul>
    <li>anytext</li>
    <li>sometext</li>
    <li>text</li>
</ul>

Thanks.

+5  A: 

Use uasort():

<?php
$hello = array(
  'text' => array('name' => 'blabla', 'num' => 10),
  'sometext' => array('name' => 'blabla', 'num' => 2),
  'anytext' => array('name' => 'blabla', 'num' => 1)
);

function sort_func($x, $y) { // our custom sorting function
  if($x['num'] == $y['num'])
    return 0; // zero return value means that the two are equal
  else if($x['num'] < $y['num'])
    return -1; // negative return value means that $x is less than $y
  else
    return 1; // positive return value means that $x is more than $y
}

uasort($hello, 'sort_func');

echo '<ul>';
foreach($hello as $key => $value)
{
  echo '<li>'.htmlspecialchars($key).'</li>';
}
echo '</ul>';
Frxstrem
how does it work?
Happy
I have fixed it now (I first misread your question..).
Frxstrem
@WorkingHard: `uasort()` will call our on comparison function (`sort_func()`) with two parameters, where our function compares them and tells `uasort()` which has the greatest value. Then `uasort()` sorts the array using this.
Frxstrem
+2  A: 

uasort is what you are looking for.

function cmp($a, $b) {
    if ($a['num'] == $b['num']) {
        return 0;
    }
    return ($a['num'] < $b['num']) ? -1 : 1;
}

uasort($hello, 'cmp');
dev-null-dweller