【问题标题】:How to do hierarchical sorting in PHP array? [duplicate]如何在 PHP 数组中进行分层排序? [复制]
【发布时间】:2018-11-13 17:37:18
【问题描述】:

我想用分层键对表进行排序,但我不能:(这是一个例子:

array ( '1.1.1' => 'test1', '10.1.1' => 'test2', '2.1.1' => 'test3', 1 => 'test4', 2 => 'test5', 3 => 'test6', '0.1' => 'test7', 0 => 'test8', 10 => 'test9', )

结果必须是:

array ( '0' => 'test8', '0.1' => 'test7', '1' => 'test4', '1.1.1' => 'test1', '2' => 'test5', '2.1.1' => 'test3', '3' => 'test6',  '10' => 'test9', '10.1.1' => 'test2')

非常感谢!

我的尝试: https://notepad.pw/71vyf2f7

【问题讨论】:

  • 请向我们展示您的尝试。
  • 问题出在哪里?
  • 请刷新,我修改了我的帖子

标签: php


【解决方案1】:

你看过 uksort 吗? http://php.net/manual/en/function.uksort.php

我认为这就是你需要的

$arr = array ( '1.1.1' => 'test1', '10.1.1' => 'test2', '2.1.1' => 'test3', 1 => 'test4', 2 => 'test5', 3 => 'test6', '0.1' => 'test7', 0 => 'test8', 10 => 'test9', );



function cmp($a,$b) {
       return floatval($a) > floatval($b);
}

uksort($arr, 'cmp');

print_r($arr)

【讨论】:

  • 非常感谢! TommyBs
  • 不客气,如果答案对您有帮助,请考虑点击“勾号”以将答案标记为已接受
【解决方案2】:
<?php

$in = [
    '1.1.1' => 'test1',
    '10.1.1' => 'test2', 
    '2.1.1' => 'test3', 
    1 => 'test4', 
    2 => 'test5', 
    3 => 'test6', 
    '0.1' => 'test7', 
    0 => 'test8', 
    10 => 'test9'
];
$desired = 
[
    '0' => 'test8', 
    '0.1' => 'test7', 
    '1' => 'test4', 
    '1.1.1' => 'test1', 
    '2' => 'test5', 
    '2.1.1' => 'test3', 
    '3' => 'test6', 
    '10' => 'test9', 
    '10.1.1' => 'test2'
];

ksort($in, SORT_NATURAL);
var_dump($in === $desired);
var_export($in);

输出:

bool(true)
array (
  0 => 'test8',
  '0.1' => 'test7',
  1 => 'test4',
  '1.1.1' => 'test1',
  2 => 'test5',
  '2.1.1' => 'test3',
  3 => 'test6',
  10 => 'test9',
  '10.1.1' => 'test2',
)

【讨论】:

  • 非常感谢!进步
猜你喜欢
  • 1970-01-01
  • 2017-12-31
  • 1970-01-01
  • 2010-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-14
相关资源
最近更新 更多