2018/05/27 PHP/Python/Java No Comments PHP一个数组按另一个数组顺序排序 ##### PHP实现将一个数组按另一个数组顺序进行排序,PHP根据一个数组对另一个数组进行排序 ##### 顺序约束数据(20条): ```php $sort_list = array(20) { [0] => int(30702) [1] => int(30373) [2] => int(32110) [3] => int(32207) [4] => int(31923) [5] => int(1497) [6] => int(32003) [7] => int(30397) [8] => int(32086) [9] => int(31920) [10] => int(30795) [11] => int(31928) [12] => int(32071) [13] => int(32456) [14] => int(31224) [15] => int(32219) [16] => int(32726) [17] => int(31508) [18] => int(32381) [19] => int(41212) } ``` ##### 待排序数据(5条): ```php $data = array(5) { [1497] => array(3) { ["houseid"] => int(1497) ["price"] => int(25000) ["area"] => array(2) { ["min"] => int(81) ["max"] => int(193) } } [30373] => array(3) { ["houseid"] => int(30373) ["price"] => int(18000) ["area"] => array(2) { ["min"] => int(109) ["max"] => int(189) } } [30397] => array(3) { ["houseid"] => int(30397) ["price"] => int(12000) ["area"] => array(2) { ["min"] => int(90) ["max"] => int(132) } } [30702] => array(3) { ["houseid"] => int(30702) ["price"] => int(19188) ["area"] => array(2) { ["min"] => int(0) ["max"] => int(188) } } [31224] => array(3) { ["houseid"] => int(31224) ["price"] => int(15149) ["area"] => array(2) { ["min"] => int(64) ["max"] => int(178) } } } ``` ##### 思路: **1、获取两者的交集:** ```php $sort_reference = array_intersect_key(array_flip($sort_list),$data); var_dump($sort_reference); 结果: array(5) { [30702] => int(0) [30373] => int(1) [1497] => int(5) [30397] => int(7) [31224] => int(14) } 函数说明: array_flip() 函数用于反转/交换数组中所有的键名以及它们关联的键值。 array_intersect_key() 函数用于比较两个(或更多个)数组的键名 ,并返回交集。 ``` **2、参考交集的数组顺序进行排序** ```php $new_list = array_replace($sort_reference,$data) var_dump($new_list); 结果: array(5) { [30702] => array(3) { ["houseid"] => int(30702) ["price"] => int(19188) ["area"] => array(2) { ["min"] => int(0) ["max"] => int(188) } } [30373] => array(3) { ["houseid"] => int(30373) ["price"] => int(18000) ["area"] => array(2) { ["min"] => int(109) ["max"] => int(189) } } [1497] => array(3) { ["houseid"] => int(1497) ["price"] => int(25000) ["area"] => array(2) { ["min"] => int(81) ["max"] => int(193) } } [30397] => array(3) { ["houseid"] => int(30397) ["price"] => int(12000) ["area"] => array(2) { ["min"] => int(90) ["max"] => int(132) } } [31224] => array(3) { ["houseid"] => int(31224) ["price"] => int(15149) ["area"] => array(2) { ["min"] => int(64) ["max"] => int(178) } } } 函数说明: array_replace() 函数使用后面数组的值替换第一个数组的值。 ``` 3、考虑json前端数据顺序(key值大小混乱),重新生成升序key值顺序 ```php $new_list = array_merge(new_list) ``` 本文最后更新于 2020-07-06 12:11:14 并被添加「php」标签,已有 6904 位童鞋阅读过。 本文作者:未来往事 本文链接:https://felixway.cn/post/658.html 本站使用「署名 4.0 国际」创作共享协议,可自由转载、引用,但需署名作者且注明文章出处 相关文章 百度主动推送API程序代码(PHP版) PHP垃圾回收与内存管理基本原理 php imagecreatefromjpeg return bool(false) php生成多级目录函数 php分卷备份恢复mysql数据库
此处评论已关闭