繁体   English   中英

使用usort在php中对数组进行自定义排序

[英]custom sorting of arrays in php using usort

我想按自定义顺序对在数组中获得的目录列表进行排序。

我确实尝试过使用usort,但没有得到理想的结果。

我也想让你解释在usort中使用的$ a和$ b。

$dir    = '/tmp';

$dir_list=scan_dir($dir);

//now this $dir_list array for the sake of this example contains the following elements

$dir_list=array('dir1','dir2','newdir2','string1');

$order=array('newdir2','dir1','string1','dir2');

//all the values in both the arrays are strings.

我在这里找到了以下解决方案,但请说明$ a,$ b和关键字“ use”的用途是什么

usort($dir_list, function ($a, $b) use ($order) 
{

    $pos_a = array_search($a['id'], $order);

    $pos_b = array_search($b['id'], $order);

    return $pos_a - $pos_b;

});

var_dump($dir_list);

usort是根据用户定义函数对数组进行排序的函数。 如果我们谈论对数组进行排序的基本概念,则数组排序总是匹配数组的两个成员,以查看哪个大于或小于或等于,因此,$ a,$ b是$ dir_list数组的两个成员(可以位于任何索引)将在排序的任何迭代中进行比较。

new关键字用于从父范围继承变量。 像上面的示例一样,您需要使用$ order,但是$ order是在匿名函数之外定义的,因此在其中使用use关键字可以将$ order变量导入匿名函数的作用域内。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM