开发者

Sort strange array by number

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):

&l开发者_开发知识库t;ul>
    <li>anytext</li>
    <li>sometext</li>
    <li>text</li>
</ul>

Thanks.


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


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');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜