PHP multi array sort by an element nested inside
倘若让数组根据[data]元素的大小重新排序:
$data = array( array( 'name'=>'Julie', 'key'=>'64489c85dc2fe0787b85cd87214b3810', 'age'=>20 ), array( 'name'=>'Martin', 'key'=>'bb07c989b57c25fd7e53395c3e118185', 'age'=>18 ), array( 'name'=>'Lucy', 'key'=>'ab3aec6d954571c7551a186ea1cd98ff', 'age'=>100 ), array( 'name'=>'Jessica', 'age'=>25, 'key'=>'e1a118c9178aa3538f39a9c8131938ed' ), );
使用 usort 重排
class itcArraySort { private $arr = array(); public function __construct($arr) { $this->arr = $arr; } public function doSort($key,$order='ASC') { $cmp = function($a, $b) use($key,$order){ if ($a[$key] == $b[$key]) return 0; if($order ==='ASC'): return ($a[$key] > $b[$key]) ? 1 : -1; else: return ($a[$key] < $b[$key]) ? 1 : -1; endif; }; if(is_array($this->arr)) { usort($this->arr, $cmp); } return $this->arr; } } $n = new itcArraySort($data);
查看结果
print_r($n->doSort('age','ASC')); /* Array ( [0] => Array ( [name] => Martin [key] => bb07c989b57c25fd7e53395c3e118185 [age] => 18 ) [1] => Array ( [name] => Julie [key] => 64489c85dc2fe0787b85cd87214b3810 [age] => 20 ) [2] => Array ( [name] => Jessica [age] => 25 [key] => e1a118c9178aa3538f39a9c8131938ed ) [3] => Array ( [name] => Lucy [key] => ab3aec6d954571c7551a186ea1cd98ff [age] => 100 ) ) */