按编号排序奇怪的数组

时间:2010-09-01 19:01:18

标签: php arrays sorting

我的阵列:

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

如何按[num]排序此数组?

应该看起来像(在回声上):

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

感谢。

2 个答案:

答案 0 :(得分:5)

使用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>';

答案 1 :(得分:2)

uasort正是您要找的。

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

uasort($hello, 'cmp');