php - 按数字对奇怪的数组进行排序

标签 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>

谢谢。

最佳答案

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

关于php - 按数字对奇怪的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3621253/

相关文章:

Php 缓冲区输出、css 和邮件

php - 不能在写上下文中使用函数返回值?

php - 本地服务器和在线服务器具有相同的时间戳但结果不同 Mysql-Php

python - 使用 pandas 对数据进行排序 - 根据其他列中的值对第一列进行排序

perl - 为什么 Perl 的 "sort"不按数字顺序放置这些哈希键?

php - 每第 4 行更改 CSS

javascript - 如何从文件名中提取具有特殊字符的 ext-javascript

c - C 中的 malloc,但使用多维数组语法

c# - 按文化排序未按预期工作

python - 如何从 Python 数组中删除值,对它们执行操作,然后将它们替换到原始数组中